blob: 0df2899855c589a6b1f4fba1412412952c354862 [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"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.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.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument *Params, unsigned NumParams,
91 const TemplateArgument *Args, unsigned NumArgs,
92 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000093 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +000095
Douglas Gregor199d9912009-06-05 00:53:49 +000096/// \brief If the given expression is of a form that permits the deduction
97/// of a non-type template parameter, return the declaration of that
98/// non-type template parameter.
99static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
100 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
101 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Douglas Gregor199d9912009-06-05 00:53:49 +0000103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
104 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Douglas Gregor199d9912009-06-05 00:53:49 +0000106 return 0;
107}
108
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000109/// \brief Determine whether two declaration pointers refer to the same
110/// declaration.
111static bool isSameDeclaration(Decl *X, Decl *Y) {
112 if (!X || !Y)
113 return !X && !Y;
114
115 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
116 X = NX->getUnderlyingDecl();
117 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
118 Y = NY->getUnderlyingDecl();
119
120 return X->getCanonicalDecl() == Y->getCanonicalDecl();
121}
122
123/// \brief Verify that the given, deduced template arguments are compatible.
124///
125/// \returns The deduced template argument, or a NULL template argument if
126/// the deduced template arguments were incompatible.
127static DeducedTemplateArgument
128checkDeducedTemplateArguments(ASTContext &Context,
129 const DeducedTemplateArgument &X,
130 const DeducedTemplateArgument &Y) {
131 // We have no deduction for one or both of the arguments; they're compatible.
132 if (X.isNull())
133 return Y;
134 if (Y.isNull())
135 return X;
136
137 switch (X.getKind()) {
138 case TemplateArgument::Null:
139 llvm_unreachable("Non-deduced template arguments handled above");
140
141 case TemplateArgument::Type:
142 // If two template type arguments have the same type, they're compatible.
143 if (Y.getKind() == TemplateArgument::Type &&
144 Context.hasSameType(X.getAsType(), Y.getAsType()))
145 return X;
146
147 return DeducedTemplateArgument();
148
149 case TemplateArgument::Integral:
150 // If we deduced a constant in one case and either a dependent expression or
151 // declaration in another case, keep the integral constant.
152 // If both are integral constants with the same value, keep that value.
153 if (Y.getKind() == TemplateArgument::Expression ||
154 Y.getKind() == TemplateArgument::Declaration ||
155 (Y.getKind() == TemplateArgument::Integral &&
156 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
157 return DeducedTemplateArgument(X,
158 X.wasDeducedFromArrayBound() &&
159 Y.wasDeducedFromArrayBound());
160
161 // All other combinations are incompatible.
162 return DeducedTemplateArgument();
163
164 case TemplateArgument::Template:
165 if (Y.getKind() == TemplateArgument::Template &&
166 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
167 return X;
168
169 // All other combinations are incompatible.
170 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000171
172 case TemplateArgument::TemplateExpansion:
173 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
174 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
175 Y.getAsTemplateOrTemplatePattern()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
180
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000181 case TemplateArgument::Expression:
182 // If we deduced a dependent expression in one case and either an integral
183 // constant or a declaration in another case, keep the integral constant
184 // or declaration.
185 if (Y.getKind() == TemplateArgument::Integral ||
186 Y.getKind() == TemplateArgument::Declaration)
187 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
188 Y.wasDeducedFromArrayBound());
189
190 if (Y.getKind() == TemplateArgument::Expression) {
191 // Compare the expressions for equality
192 llvm::FoldingSetNodeID ID1, ID2;
193 X.getAsExpr()->Profile(ID1, Context, true);
194 Y.getAsExpr()->Profile(ID2, Context, true);
195 if (ID1 == ID2)
196 return X;
197 }
198
199 // All other combinations are incompatible.
200 return DeducedTemplateArgument();
201
202 case TemplateArgument::Declaration:
203 // If we deduced a declaration and a dependent expression, keep the
204 // declaration.
205 if (Y.getKind() == TemplateArgument::Expression)
206 return X;
207
208 // If we deduced a declaration and an integral constant, keep the
209 // integral constant.
210 if (Y.getKind() == TemplateArgument::Integral)
211 return Y;
212
213 // If we deduced two declarations, make sure they they refer to the
214 // same declaration.
215 if (Y.getKind() == TemplateArgument::Declaration &&
216 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
217 return X;
218
219 // All other combinations are incompatible.
220 return DeducedTemplateArgument();
221
222 case TemplateArgument::Pack:
223 if (Y.getKind() != TemplateArgument::Pack ||
224 X.pack_size() != Y.pack_size())
225 return DeducedTemplateArgument();
226
227 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
228 XAEnd = X.pack_end(),
229 YA = Y.pack_begin();
230 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000231 if (checkDeducedTemplateArguments(Context,
232 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
233 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
234 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000235 return DeducedTemplateArgument();
236 }
237
238 return X;
239 }
240
241 return DeducedTemplateArgument();
242}
243
Mike Stump1eb44332009-09-09 15:08:12 +0000244/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000245/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000246static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000247DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000248 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000249 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000250 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000251 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000252 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000253 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000254 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000256 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
257 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
258 Deduced[NTTP->getIndex()],
259 NewDeduced);
260 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000261 Info.Param = NTTP;
262 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000263 Info.SecondArg = NewDeduced;
264 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000265 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000266
267 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000268 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000269}
270
Mike Stump1eb44332009-09-09 15:08:12 +0000271/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000272/// from the given type- or value-dependent expression.
273///
274/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000275static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000276DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 NonTypeTemplateParmDecl *NTTP,
278 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000279 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000280 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000281 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000282 "Cannot deduce non-type template argument with depth > 0");
283 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
284 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000286 DeducedTemplateArgument NewDeduced(Value);
287 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
288 Deduced[NTTP->getIndex()],
289 NewDeduced);
290
291 if (Result.isNull()) {
292 Info.Param = NTTP;
293 Info.FirstArg = Deduced[NTTP->getIndex()];
294 Info.SecondArg = NewDeduced;
295 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000296 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000297
298 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000299 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000300}
301
Douglas Gregor15755cb2009-11-13 23:45:44 +0000302/// \brief Deduce the value of the given non-type template parameter
303/// from the given declaration.
304///
305/// \returns true if deduction succeeded, false otherwise.
306static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000307DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000308 NonTypeTemplateParmDecl *NTTP,
309 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000310 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000311 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000312 assert(NTTP->getDepth() == 0 &&
313 "Cannot deduce non-type template argument with depth > 0");
314
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000315 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
316 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
317 Deduced[NTTP->getIndex()],
318 NewDeduced);
319 if (Result.isNull()) {
320 Info.Param = NTTP;
321 Info.FirstArg = Deduced[NTTP->getIndex()];
322 Info.SecondArg = NewDeduced;
323 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000324 }
325
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000326 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000327 return Sema::TDK_Success;
328}
329
Douglas Gregorf67875d2009-06-12 18:26:56 +0000330static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000331DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000332 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000333 TemplateName Param,
334 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000335 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000336 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000337 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000338 if (!ParamDecl) {
339 // The parameter type is dependent and is not a template template parameter,
340 // so there is nothing that we can deduce.
341 return Sema::TDK_Success;
342 }
343
344 if (TemplateTemplateParmDecl *TempParam
345 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000346 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
347 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
348 Deduced[TempParam->getIndex()],
349 NewDeduced);
350 if (Result.isNull()) {
351 Info.Param = TempParam;
352 Info.FirstArg = Deduced[TempParam->getIndex()];
353 Info.SecondArg = NewDeduced;
354 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000355 }
356
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000357 Deduced[TempParam->getIndex()] = Result;
358 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000359 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000360
361 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000362 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000363 return Sema::TDK_Success;
364
365 // Mismatch of non-dependent template parameter to argument.
366 Info.FirstArg = TemplateArgument(Param);
367 Info.SecondArg = TemplateArgument(Arg);
368 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000369}
370
Mike Stump1eb44332009-09-09 15:08:12 +0000371/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000372/// type (which is a template-id) with the template argument type.
373///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000374/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000375///
376/// \param TemplateParams the template parameters that we are deducing
377///
378/// \param Param the parameter type
379///
380/// \param Arg the argument type
381///
382/// \param Info information about the template argument deduction itself
383///
384/// \param Deduced the deduced template arguments
385///
386/// \returns the result of template argument deduction so far. Note that a
387/// "success" result means that template argument deduction has not yet failed,
388/// but it may still fail, later, for other reasons.
389static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000390DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000391 TemplateParameterList *TemplateParams,
392 const TemplateSpecializationType *Param,
393 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000394 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000395 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000396 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000398 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000399 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 = dyn_cast<TemplateSpecializationType>(Arg)) {
401 // Perform template argument deduction for the template name.
402 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000403 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000404 Param->getTemplateName(),
405 SpecArg->getTemplateName(),
406 Info, Deduced))
407 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000410 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000411 // argument. Ignore any missing/extra arguments, since they could be
412 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000413 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000414 Param->getArgs(), Param->getNumArgs(),
415 SpecArg->getArgs(), SpecArg->getNumArgs(),
416 Info, Deduced,
417 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000420 // If the argument type is a class template specialization, we
421 // perform template argument deduction using its template
422 // arguments.
423 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
424 if (!RecordArg)
425 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000426
427 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000428 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
429 if (!SpecArg)
430 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000432 // Perform template argument deduction for the template name.
433 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000434 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000435 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000436 Param->getTemplateName(),
437 TemplateName(SpecArg->getSpecializedTemplate()),
438 Info, Deduced))
439 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregor20a55e22010-12-22 18:17:10 +0000441 // Perform template argument deduction for the template arguments.
442 return DeduceTemplateArguments(S, TemplateParams,
443 Param->getArgs(), Param->getNumArgs(),
444 SpecArg->getTemplateArgs().data(),
445 SpecArg->getTemplateArgs().size(),
446 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000447}
448
John McCallcd05e812010-08-28 22:14:41 +0000449/// \brief Determines whether the given type is an opaque type that
450/// might be more qualified when instantiated.
451static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
452 switch (T->getTypeClass()) {
453 case Type::TypeOfExpr:
454 case Type::TypeOf:
455 case Type::DependentName:
456 case Type::Decltype:
457 case Type::UnresolvedUsing:
458 return true;
459
460 case Type::ConstantArray:
461 case Type::IncompleteArray:
462 case Type::VariableArray:
463 case Type::DependentSizedArray:
464 return IsPossiblyOpaquelyQualifiedType(
465 cast<ArrayType>(T)->getElementType());
466
467 default:
468 return false;
469 }
470}
471
Douglas Gregor500d3312009-06-26 18:27:22 +0000472/// \brief Deduce the template arguments by comparing the parameter type and
473/// the argument type (C++ [temp.deduct.type]).
474///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000475/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000476///
477/// \param TemplateParams the template parameters that we are deducing
478///
479/// \param ParamIn the parameter type
480///
481/// \param ArgIn the argument type
482///
483/// \param Info information about the template argument deduction itself
484///
485/// \param Deduced the deduced template arguments
486///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000487/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000488/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000489///
490/// \returns the result of template argument deduction so far. Note that a
491/// "success" result means that template argument deduction has not yet failed,
492/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000493static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000494DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000495 TemplateParameterList *TemplateParams,
496 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000497 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000498 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000499 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000500 // We only want to look at the canonical types, since typedefs and
501 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000502 QualType Param = S.Context.getCanonicalType(ParamIn);
503 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000504
Douglas Gregor500d3312009-06-26 18:27:22 +0000505 // C++0x [temp.deduct.call]p4 bullet 1:
506 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000507 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000508 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000509 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000510 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000511 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000512 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
513 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000514 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000517 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000518 if (!Param->isDependentType()) {
519 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
520
521 return Sema::TDK_NonDeducedMismatch;
522 }
523
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000524 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000525 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000526
Douglas Gregor199d9912009-06-05 00:53:49 +0000527 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000528 // A template type argument T, a template template argument TT or a
529 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000530 // the following forms:
531 //
532 // T
533 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000534 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000535 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000536 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000537 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000539 // If the argument type is an array type, move the qualifiers up to the
540 // top level, so they can be matched with the qualifiers on the parameter.
541 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000542 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000543 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000544 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000545 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000546 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000547 RecanonicalizeArg = true;
548 }
549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000551 // The argument type can not be less qualified than the parameter
552 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000553 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000554 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000555 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000556 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000557 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000558 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000559
560 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000561 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000562 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000563
564 // local manipulation is okay because it's canonical
565 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000566 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000567 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000569 DeducedTemplateArgument NewDeduced(DeducedType);
570 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
571 Deduced[Index],
572 NewDeduced);
573 if (Result.isNull()) {
574 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
575 Info.FirstArg = Deduced[Index];
576 Info.SecondArg = NewDeduced;
577 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000578 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000579
580 Deduced[Index] = Result;
581 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000582 }
583
Douglas Gregorf67875d2009-06-12 18:26:56 +0000584 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000585 Info.FirstArg = TemplateArgument(ParamIn);
586 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000587
Douglas Gregor508f1c82009-06-26 23:10:12 +0000588 // Check the cv-qualifiers on the parameter and argument types.
589 if (!(TDF & TDF_IgnoreQualifiers)) {
590 if (TDF & TDF_ParamWithReferenceType) {
591 if (Param.isMoreQualifiedThan(Arg))
592 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000593 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000594 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000595 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000596 }
597 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000598
Douglas Gregord560d502009-06-04 00:21:18 +0000599 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000600 // No deduction possible for these types
601 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000602 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor199d9912009-06-05 00:53:49 +0000604 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000605 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000606 QualType PointeeType;
607 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
608 PointeeType = PointerArg->getPointeeType();
609 } else if (const ObjCObjectPointerType *PointerArg
610 = Arg->getAs<ObjCObjectPointerType>()) {
611 PointeeType = PointerArg->getPointeeType();
612 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000613 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Douglas Gregor41128772009-06-26 23:27:24 +0000616 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000617 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000618 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000619 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000620 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000621 }
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Douglas Gregor199d9912009-06-05 00:53:49 +0000623 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000624 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000625 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000626 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000627 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000629 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000630 cast<LValueReferenceType>(Param)->getPointeeType(),
631 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000632 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000633 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000634
Douglas Gregor199d9912009-06-05 00:53:49 +0000635 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000636 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000637 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000638 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000639 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000641 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000642 cast<RValueReferenceType>(Param)->getPointeeType(),
643 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000644 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Douglas Gregor199d9912009-06-05 00:53:49 +0000647 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000648 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000649 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000650 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000651 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000652 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000653
John McCalle4f26e52010-08-19 00:20:19 +0000654 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000655 return DeduceTemplateArguments(S, TemplateParams,
656 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000657 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000658 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000659 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000660
661 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000662 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000663 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000664 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000665 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000666 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000667
668 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000669 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000670 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000671 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000672
John McCalle4f26e52010-08-19 00:20:19 +0000673 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000674 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000675 ConstantArrayParm->getElementType(),
676 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000677 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000678 }
679
Douglas Gregor199d9912009-06-05 00:53:49 +0000680 // type [i]
681 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000682 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000683 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000684 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
John McCalle4f26e52010-08-19 00:20:19 +0000686 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
687
Douglas Gregor199d9912009-06-05 00:53:49 +0000688 // Check the element type of the arrays
689 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000690 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000691 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000692 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000693 DependentArrayParm->getElementType(),
694 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000695 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000696 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Douglas Gregor199d9912009-06-05 00:53:49 +0000698 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000699 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000700 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
701 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000702 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
704 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000705 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000706 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000707 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000708 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000709 = dyn_cast<ConstantArrayType>(ArrayArg)) {
710 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000711 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
712 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000713 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000714 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000715 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000716 if (const DependentSizedArrayType *DependentArrayArg
717 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000718 if (DependentArrayArg->getSizeExpr())
719 return DeduceNonTypeTemplateArgument(S, NTTP,
720 DependentArrayArg->getSizeExpr(),
721 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Douglas Gregor199d9912009-06-05 00:53:49 +0000723 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000724 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
727 // type(*)(T)
728 // T(*)()
729 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000730 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000731 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000732 dyn_cast<FunctionProtoType>(Arg);
733 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000734 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
736 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000737 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000738
Mike Stump1eb44332009-09-09 15:08:12 +0000739 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000740 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000741 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000743 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000744 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000746 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000747 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000748
Anders Carlssona27fad52009-06-08 15:19:08 +0000749 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000750 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000751 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000752 FunctionProtoParam->getResultType(),
753 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000754 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000755 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Anders Carlssona27fad52009-06-08 15:19:08 +0000757 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
758 // Check argument types.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000759 // FIXME: Variadic templates.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000760 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000761 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000762 FunctionProtoParam->getArgType(I),
763 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000764 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000765 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregorf67875d2009-06-12 18:26:56 +0000768 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
John McCall3cb0ebd2010-03-10 03:28:59 +0000771 case Type::InjectedClassName: {
772 // Treat a template's injected-class-name as if the template
773 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000774 Param = cast<InjectedClassNameType>(Param)
775 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000776 assert(isa<TemplateSpecializationType>(Param) &&
777 "injected class name is not a template specialization type");
778 // fall through
779 }
780
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000781 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000782 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000783 // TT<T>
784 // TT<i>
785 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000786 case Type::TemplateSpecialization: {
787 const TemplateSpecializationType *SpecParam
788 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000790 // Try to deduce template arguments from the template-id.
791 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000792 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000793 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000795 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000796 // C++ [temp.deduct.call]p3b3:
797 // If P is a class, and P has the form template-id, then A can be a
798 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000799 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000800 // class pointed to by the deduced A.
801 //
802 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000803 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000804 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000805 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
806 // We cannot inspect base classes as part of deduction when the type
807 // is incomplete, so either instantiate any templates necessary to
808 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000809 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000810 return Result;
811
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000812 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000813 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000814 // ToVisit is our stack of records that we still need to visit.
815 llvm::SmallPtrSet<const RecordType *, 8> Visited;
816 llvm::SmallVector<const RecordType *, 8> ToVisit;
817 ToVisit.push_back(RecordT);
818 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000819 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
820 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000821 while (!ToVisit.empty()) {
822 // Retrieve the next class in the inheritance hierarchy.
823 const RecordType *NextT = ToVisit.back();
824 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000826 // If we have already seen this type, skip it.
827 if (!Visited.insert(NextT))
828 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000830 // If this is a base class, try to perform template argument
831 // deduction from it.
832 if (NextT != RecordT) {
833 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000834 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000835 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000837 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000838 // note that we had some success. Otherwise, ignore any deductions
839 // from this base class.
840 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000841 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000842 DeducedOrig = Deduced;
843 }
844 else
845 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000848 // Visit base classes
849 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
850 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
851 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000852 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000853 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000854 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000855 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000856 }
857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000859 if (Successful)
860 return Sema::TDK_Success;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000865 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000866 }
867
Douglas Gregor637a4092009-06-10 23:47:09 +0000868 // T type::*
869 // T T::*
870 // T (type::*)()
871 // type (T::*)()
872 // type (type::*)(T)
873 // type (T::*)(T)
874 // T (type::*)(T)
875 // T (T::*)()
876 // T (T::*)(T)
877 case Type::MemberPointer: {
878 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
879 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
880 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000881 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000882
Douglas Gregorf67875d2009-06-12 18:26:56 +0000883 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000884 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000885 MemPtrParam->getPointeeType(),
886 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000887 Info, Deduced,
888 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000889 return Result;
890
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000891 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000892 QualType(MemPtrParam->getClass(), 0),
893 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000894 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000895 }
896
Anders Carlsson9a917e42009-06-12 22:56:54 +0000897 // (clang extension)
898 //
Mike Stump1eb44332009-09-09 15:08:12 +0000899 // type(^)(T)
900 // T(^)()
901 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000902 case Type::BlockPointer: {
903 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
904 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Anders Carlsson859ba502009-06-12 16:23:10 +0000906 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000907 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000909 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000910 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000911 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000912 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000913 }
914
Douglas Gregor637a4092009-06-10 23:47:09 +0000915 case Type::TypeOfExpr:
916 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000917 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000918 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000919 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000920
Douglas Gregord560d502009-06-04 00:21:18 +0000921 default:
922 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000923 }
924
925 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000926 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000927}
928
Douglas Gregorf67875d2009-06-12 18:26:56 +0000929static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000930DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000931 TemplateParameterList *TemplateParams,
932 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000933 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000934 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000935 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000936 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000937 case TemplateArgument::Null:
938 assert(false && "Null template argument in parameter list");
939 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000940
941 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000942 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000943 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000944 Arg.getAsType(), Info, Deduced, 0);
945 Info.FirstArg = Param;
946 Info.SecondArg = Arg;
947 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +0000948
Douglas Gregor788cd062009-11-11 01:00:40 +0000949 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000950 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000951 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000952 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000953 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000954 Info.FirstArg = Param;
955 Info.SecondArg = Arg;
956 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +0000957
958 case TemplateArgument::TemplateExpansion:
959 llvm_unreachable("caller should handle pack expansions");
960 break;
Douglas Gregor788cd062009-11-11 01:00:40 +0000961
Douglas Gregor199d9912009-06-05 00:53:49 +0000962 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000963 if (Arg.getKind() == TemplateArgument::Declaration &&
964 Param.getAsDecl()->getCanonicalDecl() ==
965 Arg.getAsDecl()->getCanonicalDecl())
966 return Sema::TDK_Success;
967
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 Info.FirstArg = Param;
969 Info.SecondArg = Arg;
970 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Douglas Gregor199d9912009-06-05 00:53:49 +0000972 case TemplateArgument::Integral:
973 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000974 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000975 return Sema::TDK_Success;
976
977 Info.FirstArg = Param;
978 Info.SecondArg = Arg;
979 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000980 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000981
982 if (Arg.getKind() == TemplateArgument::Expression) {
983 Info.FirstArg = Param;
984 Info.SecondArg = Arg;
985 return Sema::TDK_NonDeducedMismatch;
986 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000987
Douglas Gregorf67875d2009-06-12 18:26:56 +0000988 Info.FirstArg = Param;
989 Info.SecondArg = Arg;
990 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Douglas Gregor199d9912009-06-05 00:53:49 +0000992 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000993 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000994 = getDeducedParameterFromExpr(Param.getAsExpr())) {
995 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000996 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000997 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000998 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000999 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001000 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001001 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001002 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001003 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001004 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001005 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001006 Info, Deduced);
1007
Douglas Gregorf67875d2009-06-12 18:26:56 +00001008 Info.FirstArg = Param;
1009 Info.SecondArg = Arg;
1010 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregor199d9912009-06-05 00:53:49 +00001013 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001014 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001015 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001016 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001017 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregorf67875d2009-06-12 18:26:56 +00001020 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001021}
1022
Douglas Gregor20a55e22010-12-22 18:17:10 +00001023/// \brief Determine whether there is a template argument to be used for
1024/// deduction.
1025///
1026/// This routine "expands" argument packs in-place, overriding its input
1027/// parameters so that \c Args[ArgIdx] will be the available template argument.
1028///
1029/// \returns true if there is another template argument (which will be at
1030/// \c Args[ArgIdx]), false otherwise.
1031static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1032 unsigned &ArgIdx,
1033 unsigned &NumArgs) {
1034 if (ArgIdx == NumArgs)
1035 return false;
1036
1037 const TemplateArgument &Arg = Args[ArgIdx];
1038 if (Arg.getKind() != TemplateArgument::Pack)
1039 return true;
1040
1041 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1042 Args = Arg.pack_begin();
1043 NumArgs = Arg.pack_size();
1044 ArgIdx = 0;
1045 return ArgIdx < NumArgs;
1046}
1047
Douglas Gregore02e2622010-12-22 21:19:48 +00001048/// \brief Retrieve the depth and index of an unexpanded parameter pack.
1049static std::pair<unsigned, unsigned>
1050getDepthAndIndex(UnexpandedParameterPack UPP) {
1051 if (const TemplateTypeParmType *TTP
1052 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
1053 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1054
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001055 NamedDecl *ND = UPP.first.get<NamedDecl *>();
1056 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001057 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1058
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001059 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001060 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
1061
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001062 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
Douglas Gregore02e2622010-12-22 21:19:48 +00001063 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1064}
1065
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001066/// \brief Helper function to build a TemplateParameter when we don't
1067/// know its type statically.
1068static TemplateParameter makeTemplateParameter(Decl *D) {
1069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1070 return TemplateParameter(TTP);
1071 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1072 return TemplateParameter(NTTP);
1073
1074 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1075}
1076
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001077/// \brief Determine whether the given set of template arguments has a pack
1078/// expansion that is not the last template argument.
1079static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1080 unsigned NumArgs) {
1081 unsigned ArgIdx = 0;
1082 while (ArgIdx < NumArgs) {
1083 const TemplateArgument &Arg = Args[ArgIdx];
1084
1085 // Unwrap argument packs.
1086 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1087 Args = Arg.pack_begin();
1088 NumArgs = Arg.pack_size();
1089 ArgIdx = 0;
1090 continue;
1091 }
1092
1093 ++ArgIdx;
1094 if (ArgIdx == NumArgs)
1095 return false;
1096
1097 if (Arg.isPackExpansion())
1098 return true;
1099 }
1100
1101 return false;
1102}
1103
Douglas Gregor20a55e22010-12-22 18:17:10 +00001104static Sema::TemplateDeductionResult
1105DeduceTemplateArguments(Sema &S,
1106 TemplateParameterList *TemplateParams,
1107 const TemplateArgument *Params, unsigned NumParams,
1108 const TemplateArgument *Args, unsigned NumArgs,
1109 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001110 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1111 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001112 // C++0x [temp.deduct.type]p9:
1113 // If the template argument list of P contains a pack expansion that is not
1114 // the last template argument, the entire template argument list is a
1115 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001116 if (hasPackExpansionBeforeEnd(Params, NumParams))
1117 return Sema::TDK_Success;
1118
Douglas Gregore02e2622010-12-22 21:19:48 +00001119 // C++0x [temp.deduct.type]p9:
1120 // If P has a form that contains <T> or <i>, then each argument Pi of the
1121 // respective template argument list P is compared with the corresponding
1122 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001123 unsigned ArgIdx = 0, ParamIdx = 0;
1124 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1125 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001126 // FIXME: Variadic templates.
1127 // What do we do if the argument is a pack expansion?
1128
Douglas Gregor20a55e22010-12-22 18:17:10 +00001129 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001130 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001131
1132 // Check whether we have enough arguments.
1133 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001134 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1135 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001136
Douglas Gregore02e2622010-12-22 21:19:48 +00001137 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001138 if (Sema::TemplateDeductionResult Result
1139 = DeduceTemplateArguments(S, TemplateParams,
1140 Params[ParamIdx], Args[ArgIdx],
1141 Info, Deduced))
1142 return Result;
1143
1144 // Move to the next argument.
1145 ++ArgIdx;
1146 continue;
1147 }
1148
Douglas Gregore02e2622010-12-22 21:19:48 +00001149 // The parameter is a pack expansion.
1150
1151 // C++0x [temp.deduct.type]p9:
1152 // If Pi is a pack expansion, then the pattern of Pi is compared with
1153 // each remaining argument in the template argument list of A. Each
1154 // comparison deduces template arguments for subsequent positions in the
1155 // template parameter packs expanded by Pi.
1156 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1157
1158 // Compute the set of template parameter indices that correspond to
1159 // parameter packs expanded by the pack expansion.
1160 llvm::SmallVector<unsigned, 2> PackIndices;
1161 {
1162 llvm::BitVector SawIndices(TemplateParams->size());
1163 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1164 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1165 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1166 unsigned Depth, Index;
1167 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1168 if (Depth == 0 && !SawIndices[Index]) {
1169 SawIndices[Index] = true;
1170 PackIndices.push_back(Index);
1171 }
1172 }
1173 }
1174 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1175
1176 // FIXME: If there are no remaining arguments, we can bail out early
1177 // and set any deduced parameter packs to an empty argument pack.
1178 // The latter part of this is a (minor) correctness issue.
1179
1180 // Save the deduced template arguments for each parameter pack expanded
1181 // by this pack expansion, then clear out the deduction.
1182 llvm::SmallVector<DeducedTemplateArgument, 2>
1183 SavedPacks(PackIndices.size());
1184 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1185 SavedPacks[I] = Deduced[PackIndices[I]];
1186 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1187 }
1188
1189 // Keep track of the deduced template arguments for each parameter pack
1190 // expanded by this pack expansion (the outer index) and for each
1191 // template argument (the inner SmallVectors).
1192 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1193 NewlyDeducedPacks(PackIndices.size());
1194 bool HasAnyArguments = false;
1195 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1196 HasAnyArguments = true;
1197
1198 // Deduce template arguments from the pattern.
1199 if (Sema::TemplateDeductionResult Result
1200 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1201 Info, Deduced))
1202 return Result;
1203
1204 // Capture the deduced template arguments for each parameter pack expanded
1205 // by this pack expansion, add them to the list of arguments we've deduced
1206 // for that pack, then clear out the deduced argument.
1207 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1208 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1209 if (!DeducedArg.isNull()) {
1210 NewlyDeducedPacks[I].push_back(DeducedArg);
1211 DeducedArg = DeducedTemplateArgument();
1212 }
1213 }
1214
1215 ++ArgIdx;
1216 }
1217
1218 // Build argument packs for each of the parameter packs expanded by this
1219 // pack expansion.
1220 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1221 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1222 // We were not able to deduce anything for this parameter pack,
1223 // so just restore the saved argument pack.
1224 Deduced[PackIndices[I]] = SavedPacks[I];
1225 continue;
1226 }
1227
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001228 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001229
1230 if (NewlyDeducedPacks[I].empty()) {
1231 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001232 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1233 } else {
1234 TemplateArgument *ArgumentPack
1235 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1236 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1237 ArgumentPack);
1238 NewPack
1239 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001240 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001241 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1242 }
1243
1244 DeducedTemplateArgument Result
1245 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1246 if (Result.isNull()) {
1247 Info.Param
1248 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1249 Info.FirstArg = SavedPacks[I];
1250 Info.SecondArg = NewPack;
1251 return Sema::TDK_Inconsistent;
1252 }
1253
1254 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001255 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001256 }
1257
1258 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001259 if (NumberOfArgumentsMustMatch &&
1260 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001261 return Sema::TDK_TooManyArguments;
1262
1263 return Sema::TDK_Success;
1264}
1265
Mike Stump1eb44332009-09-09 15:08:12 +00001266static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001267DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001268 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001269 const TemplateArgumentList &ParamList,
1270 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001271 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001272 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001273 return DeduceTemplateArguments(S, TemplateParams,
1274 ParamList.data(), ParamList.size(),
1275 ArgList.data(), ArgList.size(),
1276 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001277}
1278
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001279/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001280static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001281 const TemplateArgument &X,
1282 const TemplateArgument &Y) {
1283 if (X.getKind() != Y.getKind())
1284 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001286 switch (X.getKind()) {
1287 case TemplateArgument::Null:
1288 assert(false && "Comparing NULL template argument");
1289 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001291 case TemplateArgument::Type:
1292 return Context.getCanonicalType(X.getAsType()) ==
1293 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001295 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001296 return X.getAsDecl()->getCanonicalDecl() ==
1297 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregor788cd062009-11-11 01:00:40 +00001299 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001300 case TemplateArgument::TemplateExpansion:
1301 return Context.getCanonicalTemplateName(
1302 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1303 Context.getCanonicalTemplateName(
1304 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001305
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001306 case TemplateArgument::Integral:
1307 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Douglas Gregor788cd062009-11-11 01:00:40 +00001309 case TemplateArgument::Expression: {
1310 llvm::FoldingSetNodeID XID, YID;
1311 X.getAsExpr()->Profile(XID, Context, true);
1312 Y.getAsExpr()->Profile(YID, Context, true);
1313 return XID == YID;
1314 }
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001316 case TemplateArgument::Pack:
1317 if (X.pack_size() != Y.pack_size())
1318 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001319
1320 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1321 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001322 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001323 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001324 if (!isSameTemplateArg(Context, *XP, *YP))
1325 return false;
1326
1327 return true;
1328 }
1329
1330 return false;
1331}
1332
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001333/// \brief Allocate a TemplateArgumentLoc where all locations have
1334/// been initialized to the given location.
1335///
1336/// \param S The semantic analysis object.
1337///
1338/// \param The template argument we are producing template argument
1339/// location information for.
1340///
1341/// \param NTTPType For a declaration template argument, the type of
1342/// the non-type template parameter that corresponds to this template
1343/// argument.
1344///
1345/// \param Loc The source location to use for the resulting template
1346/// argument.
1347static TemplateArgumentLoc
1348getTrivialTemplateArgumentLoc(Sema &S,
1349 const TemplateArgument &Arg,
1350 QualType NTTPType,
1351 SourceLocation Loc) {
1352 switch (Arg.getKind()) {
1353 case TemplateArgument::Null:
1354 llvm_unreachable("Can't get a NULL template argument here");
1355 break;
1356
1357 case TemplateArgument::Type:
1358 return TemplateArgumentLoc(Arg,
1359 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1360
1361 case TemplateArgument::Declaration: {
1362 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001363 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001364 .takeAs<Expr>();
1365 return TemplateArgumentLoc(TemplateArgument(E), E);
1366 }
1367
1368 case TemplateArgument::Integral: {
1369 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001370 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001371 return TemplateArgumentLoc(TemplateArgument(E), E);
1372 }
1373
1374 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001375 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1376
1377 case TemplateArgument::TemplateExpansion:
1378 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1379
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001380 case TemplateArgument::Expression:
1381 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1382
1383 case TemplateArgument::Pack:
1384 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1385 }
1386
1387 return TemplateArgumentLoc();
1388}
1389
1390
1391/// \brief Convert the given deduced template argument and add it to the set of
1392/// fully-converted template arguments.
1393static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1394 DeducedTemplateArgument Arg,
1395 NamedDecl *Template,
1396 QualType NTTPType,
1397 TemplateDeductionInfo &Info,
1398 bool InFunctionTemplate,
1399 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1400 if (Arg.getKind() == TemplateArgument::Pack) {
1401 // This is a template argument pack, so check each of its arguments against
1402 // the template parameter.
1403 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1404 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001405 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001406 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001407 // When converting the deduced template argument, append it to the
1408 // general output list. We need to do this so that the template argument
1409 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001410 DeducedTemplateArgument InnerArg(*PA);
1411 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1412 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1413 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001414 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001415 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001416
1417 // Move the converted template argument into our argument pack.
1418 PackedArgsBuilder.push_back(Output.back());
1419 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001420 }
1421
1422 // Create the resulting argument pack.
1423 TemplateArgument *PackedArgs = 0;
1424 if (!PackedArgsBuilder.empty()) {
1425 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1426 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1427 }
1428 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1429 return false;
1430 }
1431
1432 // Convert the deduced template argument into a template
1433 // argument that we can check, almost as if the user had written
1434 // the template argument explicitly.
1435 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1436 Info.getLocation());
1437
1438 // Check the template argument, converting it as necessary.
1439 return S.CheckTemplateArgument(Param, ArgLoc,
1440 Template,
1441 Template->getLocation(),
1442 Template->getSourceRange().getEnd(),
1443 Output,
1444 InFunctionTemplate
1445 ? (Arg.wasDeducedFromArrayBound()
1446 ? Sema::CTAK_DeducedFromArrayBound
1447 : Sema::CTAK_Deduced)
1448 : Sema::CTAK_Specified);
1449}
1450
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001451/// Complete template argument deduction for a class template partial
1452/// specialization.
1453static Sema::TemplateDeductionResult
1454FinishTemplateArgumentDeduction(Sema &S,
1455 ClassTemplatePartialSpecializationDecl *Partial,
1456 const TemplateArgumentList &TemplateArgs,
1457 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001458 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001459 // Trap errors.
1460 Sema::SFINAETrap Trap(S);
1461
1462 Sema::ContextRAII SavedContext(S, Partial);
1463
1464 // C++ [temp.deduct.type]p2:
1465 // [...] or if any template argument remains neither deduced nor
1466 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001467 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001468 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1469 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001470 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001471 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001472 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001473 return Sema::TDK_Incomplete;
1474 }
1475
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001476 // We have deduced this argument, so it still needs to be
1477 // checked and converted.
1478
1479 // First, for a non-type template parameter type that is
1480 // initialized by a declaration, we need the type of the
1481 // corresponding non-type template parameter.
1482 QualType NTTPType;
1483 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001484 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001485 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001486 if (NTTPType->isDependentType()) {
1487 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1488 Builder.data(), Builder.size());
1489 NTTPType = S.SubstType(NTTPType,
1490 MultiLevelTemplateArgumentList(TemplateArgs),
1491 NTTP->getLocation(),
1492 NTTP->getDeclName());
1493 if (NTTPType.isNull()) {
1494 Info.Param = makeTemplateParameter(Param);
1495 // FIXME: These template arguments are temporary. Free them!
1496 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1497 Builder.data(),
1498 Builder.size()));
1499 return Sema::TDK_SubstitutionFailure;
1500 }
1501 }
1502 }
1503
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001504 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1505 Partial, NTTPType, Info, false,
1506 Builder)) {
1507 Info.Param = makeTemplateParameter(Param);
1508 // FIXME: These template arguments are temporary. Free them!
1509 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1510 Builder.size()));
1511 return Sema::TDK_SubstitutionFailure;
1512 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001513 }
1514
1515 // Form the template argument list from the deduced template arguments.
1516 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001517 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1518 Builder.size());
1519
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001520 Info.reset(DeducedArgumentList);
1521
1522 // Substitute the deduced template arguments into the template
1523 // arguments of the class template partial specialization, and
1524 // verify that the instantiated template arguments are both valid
1525 // and are equivalent to the template arguments originally provided
1526 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001527 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001528 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1529 const TemplateArgumentLoc *PartialTemplateArgs
1530 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001531
1532 // Note that we don't provide the langle and rangle locations.
1533 TemplateArgumentListInfo InstArgs;
1534
Douglas Gregore02e2622010-12-22 21:19:48 +00001535 if (S.Subst(PartialTemplateArgs,
1536 Partial->getNumTemplateArgsAsWritten(),
1537 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1538 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1539 if (ParamIdx >= Partial->getTemplateParameters()->size())
1540 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1541
1542 Decl *Param
1543 = const_cast<NamedDecl *>(
1544 Partial->getTemplateParameters()->getParam(ParamIdx));
1545 Info.Param = makeTemplateParameter(Param);
1546 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1547 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001548 }
1549
Douglas Gregor910f8002010-11-07 23:05:16 +00001550 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001551 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001552 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001553 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001554
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001555 TemplateParameterList *TemplateParams
1556 = ClassTemplate->getTemplateParameters();
1557 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001558 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001559 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001560 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001561 Info.FirstArg = TemplateArgs[I];
1562 Info.SecondArg = InstArg;
1563 return Sema::TDK_NonDeducedMismatch;
1564 }
1565 }
1566
1567 if (Trap.hasErrorOccurred())
1568 return Sema::TDK_SubstitutionFailure;
1569
1570 return Sema::TDK_Success;
1571}
1572
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001573/// \brief Perform template argument deduction to determine whether
1574/// the given template arguments match the given class template
1575/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001576Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001577Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001578 const TemplateArgumentList &TemplateArgs,
1579 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001580 // C++ [temp.class.spec.match]p2:
1581 // A partial specialization matches a given actual template
1582 // argument list if the template arguments of the partial
1583 // specialization can be deduced from the actual template argument
1584 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001585 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001586 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001587 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001588 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001589 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001590 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001591 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001592 TemplateArgs, Info, Deduced))
1593 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001594
Douglas Gregor637a4092009-06-10 23:47:09 +00001595 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001596 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001597 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001598 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001599
Douglas Gregorbb260412009-06-14 08:02:22 +00001600 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001601 return Sema::TDK_SubstitutionFailure;
1602
1603 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1604 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001605}
Douglas Gregor031a5882009-06-13 00:26:55 +00001606
Douglas Gregor41128772009-06-26 23:27:24 +00001607/// \brief Determine whether the given type T is a simple-template-id type.
1608static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001609 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001610 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001611 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Douglas Gregor41128772009-06-26 23:27:24 +00001613 return false;
1614}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001615
1616/// \brief Substitute the explicitly-provided template arguments into the
1617/// given function template according to C++ [temp.arg.explicit].
1618///
1619/// \param FunctionTemplate the function template into which the explicit
1620/// template arguments will be substituted.
1621///
Mike Stump1eb44332009-09-09 15:08:12 +00001622/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001623/// arguments.
1624///
Mike Stump1eb44332009-09-09 15:08:12 +00001625/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001626/// with the converted and checked explicit template arguments.
1627///
Mike Stump1eb44332009-09-09 15:08:12 +00001628/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001629/// parameters.
1630///
1631/// \param FunctionType if non-NULL, the result type of the function template
1632/// will also be instantiated and the pointed-to value will be updated with
1633/// the instantiated function type.
1634///
1635/// \param Info if substitution fails for any reason, this object will be
1636/// populated with more information about the failure.
1637///
1638/// \returns TDK_Success if substitution was successful, or some failure
1639/// condition.
1640Sema::TemplateDeductionResult
1641Sema::SubstituteExplicitTemplateArguments(
1642 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001643 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001644 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001645 llvm::SmallVectorImpl<QualType> &ParamTypes,
1646 QualType *FunctionType,
1647 TemplateDeductionInfo &Info) {
1648 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1649 TemplateParameterList *TemplateParams
1650 = FunctionTemplate->getTemplateParameters();
1651
John McCalld5532b62009-11-23 01:53:49 +00001652 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001653 // No arguments to substitute; just copy over the parameter types and
1654 // fill in the function type.
1655 for (FunctionDecl::param_iterator P = Function->param_begin(),
1656 PEnd = Function->param_end();
1657 P != PEnd;
1658 ++P)
1659 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Douglas Gregor83314aa2009-07-08 20:55:45 +00001661 if (FunctionType)
1662 *FunctionType = Function->getType();
1663 return TDK_Success;
1664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Douglas Gregor83314aa2009-07-08 20:55:45 +00001666 // Substitution of the explicit template arguments into a function template
1667 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001668 SFINAETrap Trap(*this);
1669
Douglas Gregor83314aa2009-07-08 20:55:45 +00001670 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001671 // Template arguments that are present shall be specified in the
1672 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001673 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001674 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001675 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001676
1677 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001678 // explicitly-specified template arguments against this function template,
1679 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001680 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001681 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001682 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1683 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001684 if (Inst)
1685 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Douglas Gregor83314aa2009-07-08 20:55:45 +00001687 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001688 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001689 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001690 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001691 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001692 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001693 if (Index >= TemplateParams->size())
1694 Index = TemplateParams->size() - 1;
1695 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001696 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor83314aa2009-07-08 20:55:45 +00001699 // Form the template argument list from the explicitly-specified
1700 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001701 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001702 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001703 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
John McCalldf41f182010-10-12 19:40:14 +00001705 // Template argument deduction and the final substitution should be
1706 // done in the context of the templated declaration. Explicit
1707 // argument substitution, on the other hand, needs to happen in the
1708 // calling context.
1709 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1710
Douglas Gregor83314aa2009-07-08 20:55:45 +00001711 // Instantiate the types of each of the function parameters given the
1712 // explicitly-specified template arguments.
1713 for (FunctionDecl::param_iterator P = Function->param_begin(),
1714 PEnd = Function->param_end();
1715 P != PEnd;
1716 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001717 QualType ParamType
1718 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001719 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1720 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001721 if (ParamType.isNull() || Trap.hasErrorOccurred())
1722 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregor83314aa2009-07-08 20:55:45 +00001724 ParamTypes.push_back(ParamType);
1725 }
1726
1727 // If the caller wants a full function type back, instantiate the return
1728 // type and form that function type.
1729 if (FunctionType) {
1730 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001731 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001732 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001733 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001734
1735 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001736 = SubstType(Proto->getResultType(),
1737 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1738 Function->getTypeSpecStartLoc(),
1739 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001740 if (ResultType.isNull() || Trap.hasErrorOccurred())
1741 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001742
1743 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001744 ParamTypes.data(), ParamTypes.size(),
1745 Proto->isVariadic(),
1746 Proto->getTypeQuals(),
1747 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001748 Function->getDeclName(),
1749 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001750 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1751 return TDK_SubstitutionFailure;
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Douglas Gregor83314aa2009-07-08 20:55:45 +00001754 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001755 // Trailing template arguments that can be deduced (14.8.2) may be
1756 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001757 // template arguments can be deduced, they may all be omitted; in this
1758 // case, the empty template argument list <> itself may also be omitted.
1759 //
1760 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001761 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001762 Deduced.reserve(TemplateParams->size());
1763 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001764 Deduced.push_back(ExplicitArgumentList->get(I));
1765
Douglas Gregor83314aa2009-07-08 20:55:45 +00001766 return TDK_Success;
1767}
1768
Mike Stump1eb44332009-09-09 15:08:12 +00001769/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001770/// checking the deduced template arguments for completeness and forming
1771/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001772Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001773Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001774 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1775 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001776 FunctionDecl *&Specialization,
1777 TemplateDeductionInfo &Info) {
1778 TemplateParameterList *TemplateParams
1779 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Douglas Gregor83314aa2009-07-08 20:55:45 +00001781 // Template argument deduction for function templates in a SFINAE context.
1782 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001783 SFINAETrap Trap(*this);
1784
Douglas Gregor83314aa2009-07-08 20:55:45 +00001785 // Enter a new template instantiation context while we instantiate the
1786 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001787 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001788 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001789 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1790 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001791 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001792 return TDK_InstantiationDepth;
1793
John McCall96db3102010-04-29 01:18:58 +00001794 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001795
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001796 // C++ [temp.deduct.type]p2:
1797 // [...] or if any template argument remains neither deduced nor
1798 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001799 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001800 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1801 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001802
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001803 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001804 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001805 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001806 // argument, because it was explicitly-specified. Just record the
1807 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001808 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001809 continue;
1810 }
1811
1812 // We have deduced this argument, so it still needs to be
1813 // checked and converted.
1814
1815 // First, for a non-type template parameter type that is
1816 // initialized by a declaration, we need the type of the
1817 // corresponding non-type template parameter.
1818 QualType NTTPType;
1819 if (NonTypeTemplateParmDecl *NTTP
1820 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001821 NTTPType = NTTP->getType();
1822 if (NTTPType->isDependentType()) {
1823 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1824 Builder.data(), Builder.size());
1825 NTTPType = SubstType(NTTPType,
1826 MultiLevelTemplateArgumentList(TemplateArgs),
1827 NTTP->getLocation(),
1828 NTTP->getDeclName());
1829 if (NTTPType.isNull()) {
1830 Info.Param = makeTemplateParameter(Param);
1831 // FIXME: These template arguments are temporary. Free them!
1832 Info.reset(TemplateArgumentList::CreateCopy(Context,
1833 Builder.data(),
1834 Builder.size()));
1835 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00001836 }
1837 }
1838 }
1839
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001840 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
1841 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001842 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001843 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001844 // FIXME: These template arguments are temporary. Free them!
1845 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001846 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001847 return TDK_SubstitutionFailure;
1848 }
1849
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001850 continue;
1851 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001852
1853 // C++0x [temp.arg.explicit]p3:
1854 // A trailing template parameter pack (14.5.3) not otherwise deduced will
1855 // be deduced to an empty sequence of template arguments.
1856 // FIXME: Where did the word "trailing" come from?
1857 if (Param->isTemplateParameterPack()) {
1858 Builder.push_back(TemplateArgument(0, 0));
1859 continue;
1860 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001861
1862 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001863 TemplateArgumentLoc DefArg
1864 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1865 FunctionTemplate->getLocation(),
1866 FunctionTemplate->getSourceRange().getEnd(),
1867 Param,
1868 Builder);
1869
1870 // If there was no default argument, deduction is incomplete.
1871 if (DefArg.getArgument().isNull()) {
1872 Info.Param = makeTemplateParameter(
1873 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1874 return TDK_Incomplete;
1875 }
1876
1877 // Check whether we can actually use the default argument.
1878 if (CheckTemplateArgument(Param, DefArg,
1879 FunctionTemplate,
1880 FunctionTemplate->getLocation(),
1881 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001882 Builder,
1883 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001884 Info.Param = makeTemplateParameter(
1885 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001886 // FIXME: These template arguments are temporary. Free them!
1887 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1888 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001889 return TDK_SubstitutionFailure;
1890 }
1891
1892 // If we get here, we successfully used the default template argument.
1893 }
1894
1895 // Form the template argument list from the deduced template arguments.
1896 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001897 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001898 Info.reset(DeducedArgumentList);
1899
Mike Stump1eb44332009-09-09 15:08:12 +00001900 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001901 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001902 DeclContext *Owner = FunctionTemplate->getDeclContext();
1903 if (FunctionTemplate->getFriendObjectKind())
1904 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001905 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001906 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001907 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001908 if (!Specialization)
1909 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregorf8825742009-09-15 18:26:13 +00001911 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1912 FunctionTemplate->getCanonicalDecl());
1913
Mike Stump1eb44332009-09-09 15:08:12 +00001914 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001915 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001916 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1917 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001918 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Douglas Gregor83314aa2009-07-08 20:55:45 +00001920 // There may have been an error that did not prevent us from constructing a
1921 // declaration. Mark the declaration invalid and return with a substitution
1922 // failure.
1923 if (Trap.hasErrorOccurred()) {
1924 Specialization->setInvalidDecl(true);
1925 return TDK_SubstitutionFailure;
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor9b623632010-10-12 23:32:35 +00001928 // If we suppressed any diagnostics while performing template argument
1929 // deduction, and if we haven't already instantiated this declaration,
1930 // keep track of these diagnostics. They'll be emitted if this specialization
1931 // is actually used.
1932 if (Info.diag_begin() != Info.diag_end()) {
1933 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1934 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1935 if (Pos == SuppressedDiagnostics.end())
1936 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1937 .append(Info.diag_begin(), Info.diag_end());
1938 }
1939
Mike Stump1eb44332009-09-09 15:08:12 +00001940 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001941}
1942
John McCall9c72c602010-08-27 09:08:28 +00001943/// Gets the type of a function for template-argument-deducton
1944/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001945static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001946 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001947 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001948 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001949 if (Method->isInstance()) {
1950 // An instance method that's referenced in a form that doesn't
1951 // look like a member pointer is just invalid.
1952 if (!R.HasFormOfMemberPointer) return QualType();
1953
John McCalleff92132010-02-02 02:21:27 +00001954 return Context.getMemberPointerType(Fn->getType(),
1955 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001956 }
1957
1958 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001959 return Context.getPointerType(Fn->getType());
1960}
1961
1962/// Apply the deduction rules for overload sets.
1963///
1964/// \return the null type if this argument should be treated as an
1965/// undeduced context
1966static QualType
1967ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001968 Expr *Arg, QualType ParamType,
1969 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001970
1971 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001972
John McCall9c72c602010-08-27 09:08:28 +00001973 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001974
Douglas Gregor75f21af2010-08-30 21:04:23 +00001975 // C++0x [temp.deduct.call]p4
1976 unsigned TDF = 0;
1977 if (ParamWasReference)
1978 TDF |= TDF_ParamWithReferenceType;
1979 if (R.IsAddressOfOperand)
1980 TDF |= TDF_IgnoreQualifiers;
1981
John McCalleff92132010-02-02 02:21:27 +00001982 // If there were explicit template arguments, we can only find
1983 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1984 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001985 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001986 // But we can still look for an explicit specialization.
1987 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001988 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001989 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001990 return QualType();
1991 }
1992
1993 // C++0x [temp.deduct.call]p6:
1994 // When P is a function type, pointer to function type, or pointer
1995 // to member function type:
1996
1997 if (!ParamType->isFunctionType() &&
1998 !ParamType->isFunctionPointerType() &&
1999 !ParamType->isMemberFunctionPointerType())
2000 return QualType();
2001
2002 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002003 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2004 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002005 NamedDecl *D = (*I)->getUnderlyingDecl();
2006
2007 // - If the argument is an overload set containing one or more
2008 // function templates, the parameter is treated as a
2009 // non-deduced context.
2010 if (isa<FunctionTemplateDecl>(D))
2011 return QualType();
2012
2013 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002014 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2015 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002016
Douglas Gregor75f21af2010-08-30 21:04:23 +00002017 // Function-to-pointer conversion.
2018 if (!ParamWasReference && ParamType->isPointerType() &&
2019 ArgType->isFunctionType())
2020 ArgType = S.Context.getPointerType(ArgType);
2021
John McCalleff92132010-02-02 02:21:27 +00002022 // - If the argument is an overload set (not containing function
2023 // templates), trial argument deduction is attempted using each
2024 // of the members of the set. If deduction succeeds for only one
2025 // of the overload set members, that member is used as the
2026 // argument value for the deduction. If deduction succeeds for
2027 // more than one member of the overload set the parameter is
2028 // treated as a non-deduced context.
2029
2030 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2031 // Type deduction is done independently for each P/A pair, and
2032 // the deduced template argument values are then combined.
2033 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002034 llvm::SmallVector<DeducedTemplateArgument, 8>
2035 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002036 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002037 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002038 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002039 ParamType, ArgType,
2040 Info, Deduced, TDF);
2041 if (Result) continue;
2042 if (!Match.isNull()) return QualType();
2043 Match = ArgType;
2044 }
2045
2046 return Match;
2047}
2048
Douglas Gregore53060f2009-06-25 22:08:12 +00002049/// \brief Perform template argument deduction from a function call
2050/// (C++ [temp.deduct.call]).
2051///
2052/// \param FunctionTemplate the function template for which we are performing
2053/// template argument deduction.
2054///
Douglas Gregor48026d22010-01-11 18:40:55 +00002055/// \param ExplicitTemplateArguments the explicit template arguments provided
2056/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002057///
Douglas Gregore53060f2009-06-25 22:08:12 +00002058/// \param Args the function call arguments
2059///
2060/// \param NumArgs the number of arguments in Args
2061///
Douglas Gregor48026d22010-01-11 18:40:55 +00002062/// \param Name the name of the function being called. This is only significant
2063/// when the function template is a conversion function template, in which
2064/// case this routine will also perform template argument deduction based on
2065/// the function to which
2066///
Douglas Gregore53060f2009-06-25 22:08:12 +00002067/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002068/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002069/// template argument deduction.
2070///
2071/// \param Info the argument will be updated to provide additional information
2072/// about template argument deduction.
2073///
2074/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002075Sema::TemplateDeductionResult
2076Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002077 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002078 Expr **Args, unsigned NumArgs,
2079 FunctionDecl *&Specialization,
2080 TemplateDeductionInfo &Info) {
2081 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002082
Douglas Gregore53060f2009-06-25 22:08:12 +00002083 // C++ [temp.deduct.call]p1:
2084 // Template argument deduction is done by comparing each function template
2085 // parameter type (call it P) with the type of the corresponding argument
2086 // of the call (call it A) as described below.
2087 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002088 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002089 return TDK_TooFewArguments;
2090 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002091 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002092 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00002093 if (!Proto->isVariadic())
2094 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Douglas Gregore53060f2009-06-25 22:08:12 +00002096 CheckArgs = Function->getNumParams();
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002099 // The types of the parameters from which we will perform template argument
2100 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002101 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002102 TemplateParameterList *TemplateParams
2103 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002104 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002105 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002106 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002107 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002108 TemplateDeductionResult Result =
2109 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002110 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002111 Deduced,
2112 ParamTypes,
2113 0,
2114 Info);
2115 if (Result)
2116 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002117
2118 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002119 } else {
2120 // Just fill in the parameter types from the function declaration.
2121 for (unsigned I = 0; I != CheckArgs; ++I)
2122 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002125 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002126 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002127 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002128 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002129 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregor75f21af2010-08-30 21:04:23 +00002131 // C++0x [temp.deduct.call]p3:
2132 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2133 // are ignored for type deduction.
2134 if (ParamType.getCVRQualifiers())
2135 ParamType = ParamType.getLocalUnqualifiedType();
2136 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2137 if (ParamRefType) {
2138 // [...] If P is a reference type, the type referred to by P is used
2139 // for type deduction.
2140 ParamType = ParamRefType->getPointeeType();
2141 }
2142
John McCalleff92132010-02-02 02:21:27 +00002143 // Overload sets usually make this parameter an undeduced
2144 // context, but there are sometimes special circumstances.
2145 if (ArgType == Context.OverloadTy) {
2146 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002147 Args[I], ParamType,
2148 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002149 if (ArgType.isNull())
2150 continue;
2151 }
2152
Douglas Gregor75f21af2010-08-30 21:04:23 +00002153 if (ParamRefType) {
2154 // C++0x [temp.deduct.call]p3:
2155 // [...] If P is of the form T&&, where T is a template parameter, and
2156 // the argument is an lvalue, the type A& is used in place of A for
2157 // type deduction.
2158 if (ParamRefType->isRValueReferenceType() &&
2159 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002160 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002161 ArgType = Context.getLValueReferenceType(ArgType);
2162 } else {
2163 // C++ [temp.deduct.call]p2:
2164 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002165 // - If A is an array type, the pointer type produced by the
2166 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002167 // A for type deduction; otherwise,
2168 if (ArgType->isArrayType())
2169 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002170 // - If A is a function type, the pointer type produced by the
2171 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002172 // of A for type deduction; otherwise,
2173 else if (ArgType->isFunctionType())
2174 ArgType = Context.getPointerType(ArgType);
2175 else {
2176 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2177 // type are ignored for type deduction.
2178 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002179 if (ArgType.getCVRQualifiers())
2180 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002181 }
2182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Douglas Gregore53060f2009-06-25 22:08:12 +00002184 // C++0x [temp.deduct.call]p4:
2185 // In general, the deduction process attempts to find template argument
2186 // values that will make the deduced A identical to A (after the type A
2187 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002188 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Douglas Gregor508f1c82009-06-26 23:10:12 +00002190 // - If the original P is a reference type, the deduced A (i.e., the
2191 // type referred to by the reference) can be more cv-qualified than
2192 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002193 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002194 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002195 // - The transformed A can be another pointer or pointer to member
2196 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002197 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002198 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2199 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002200 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002201 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002202 // transformed A can be a derived class of the deduced A. Likewise,
2203 // if P is a pointer to a class of the form simple-template-id, the
2204 // transformed A can be a pointer to a derived class pointed to by
2205 // the deduced A.
2206 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002207 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002208 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002209 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002210 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregore53060f2009-06-25 22:08:12 +00002212 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002213 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002214 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002215 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002216 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002218 // FIXME: we need to check that the deduced A is the same as A,
2219 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002220 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002221
Mike Stump1eb44332009-09-09 15:08:12 +00002222 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002223 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002224 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002225}
2226
Douglas Gregor83314aa2009-07-08 20:55:45 +00002227/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002228/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2229/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002230///
2231/// \param FunctionTemplate the function template for which we are performing
2232/// template argument deduction.
2233///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002234/// \param ExplicitTemplateArguments the explicitly-specified template
2235/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002236///
2237/// \param ArgFunctionType the function type that will be used as the
2238/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002239/// function template's function type. This type may be NULL, if there is no
2240/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002241///
2242/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002243/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002244/// template argument deduction.
2245///
2246/// \param Info the argument will be updated to provide additional information
2247/// about template argument deduction.
2248///
2249/// \returns the result of template argument deduction.
2250Sema::TemplateDeductionResult
2251Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002252 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002253 QualType ArgFunctionType,
2254 FunctionDecl *&Specialization,
2255 TemplateDeductionInfo &Info) {
2256 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2257 TemplateParameterList *TemplateParams
2258 = FunctionTemplate->getTemplateParameters();
2259 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Douglas Gregor83314aa2009-07-08 20:55:45 +00002261 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002262 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002263 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2264 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002265 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002266 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002267 if (TemplateDeductionResult Result
2268 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002269 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002270 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002271 &FunctionType, Info))
2272 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002273
2274 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002275 }
2276
2277 // Template argument deduction for function templates in a SFINAE context.
2278 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002279 SFINAETrap Trap(*this);
2280
John McCalleff92132010-02-02 02:21:27 +00002281 Deduced.resize(TemplateParams->size());
2282
Douglas Gregor4b52e252009-12-21 23:17:24 +00002283 if (!ArgFunctionType.isNull()) {
2284 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002285 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002286 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002287 FunctionType, ArgFunctionType, Info,
2288 Deduced, 0))
2289 return Result;
2290 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002291
2292 if (TemplateDeductionResult Result
2293 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2294 NumExplicitlySpecified,
2295 Specialization, Info))
2296 return Result;
2297
2298 // If the requested function type does not match the actual type of the
2299 // specialization, template argument deduction fails.
2300 if (!ArgFunctionType.isNull() &&
2301 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2302 return TDK_NonDeducedMismatch;
2303
2304 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002305}
2306
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002307/// \brief Deduce template arguments for a templated conversion
2308/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2309/// conversion function template specialization.
2310Sema::TemplateDeductionResult
2311Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2312 QualType ToType,
2313 CXXConversionDecl *&Specialization,
2314 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002315 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002316 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2317 QualType FromType = Conv->getConversionType();
2318
2319 // Canonicalize the types for deduction.
2320 QualType P = Context.getCanonicalType(FromType);
2321 QualType A = Context.getCanonicalType(ToType);
2322
2323 // C++0x [temp.deduct.conv]p3:
2324 // If P is a reference type, the type referred to by P is used for
2325 // type deduction.
2326 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2327 P = PRef->getPointeeType();
2328
2329 // C++0x [temp.deduct.conv]p3:
2330 // If A is a reference type, the type referred to by A is used
2331 // for type deduction.
2332 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2333 A = ARef->getPointeeType();
2334 // C++ [temp.deduct.conv]p2:
2335 //
Mike Stump1eb44332009-09-09 15:08:12 +00002336 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002337 else {
2338 assert(!A->isReferenceType() && "Reference types were handled above");
2339
2340 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002341 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002342 // of P for type deduction; otherwise,
2343 if (P->isArrayType())
2344 P = Context.getArrayDecayedType(P);
2345 // - If P is a function type, the pointer type produced by the
2346 // function-to-pointer standard conversion (4.3) is used in
2347 // place of P for type deduction; otherwise,
2348 else if (P->isFunctionType())
2349 P = Context.getPointerType(P);
2350 // - If P is a cv-qualified type, the top level cv-qualifiers of
2351 // P’s type are ignored for type deduction.
2352 else
2353 P = P.getUnqualifiedType();
2354
2355 // C++0x [temp.deduct.conv]p3:
2356 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2357 // type are ignored for type deduction.
2358 A = A.getUnqualifiedType();
2359 }
2360
2361 // Template argument deduction for function templates in a SFINAE context.
2362 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002363 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002364
2365 // C++ [temp.deduct.conv]p1:
2366 // Template argument deduction is done by comparing the return
2367 // type of the template conversion function (call it P) with the
2368 // type that is required as the result of the conversion (call it
2369 // A) as described in 14.8.2.4.
2370 TemplateParameterList *TemplateParams
2371 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002372 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002373 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002374
2375 // C++0x [temp.deduct.conv]p4:
2376 // In general, the deduction process attempts to find template
2377 // argument values that will make the deduced A identical to
2378 // A. However, there are two cases that allow a difference:
2379 unsigned TDF = 0;
2380 // - If the original A is a reference type, A can be more
2381 // cv-qualified than the deduced A (i.e., the type referred to
2382 // by the reference)
2383 if (ToType->isReferenceType())
2384 TDF |= TDF_ParamWithReferenceType;
2385 // - The deduced A can be another pointer or pointer to member
2386 // type that can be converted to A via a qualification
2387 // conversion.
2388 //
2389 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2390 // both P and A are pointers or member pointers. In this case, we
2391 // just ignore cv-qualifiers completely).
2392 if ((P->isPointerType() && A->isPointerType()) ||
2393 (P->isMemberPointerType() && P->isMemberPointerType()))
2394 TDF |= TDF_IgnoreQualifiers;
2395 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002396 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002397 P, A, Info, Deduced, TDF))
2398 return Result;
2399
2400 // FIXME: we need to check that the deduced A is the same as A,
2401 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002403 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002404 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002405 FunctionDecl *Spec = 0;
2406 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002407 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2408 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002409 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2410 return Result;
2411}
2412
Douglas Gregor4b52e252009-12-21 23:17:24 +00002413/// \brief Deduce template arguments for a function template when there is
2414/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2415///
2416/// \param FunctionTemplate the function template for which we are performing
2417/// template argument deduction.
2418///
2419/// \param ExplicitTemplateArguments the explicitly-specified template
2420/// arguments.
2421///
2422/// \param Specialization if template argument deduction was successful,
2423/// this will be set to the function template specialization produced by
2424/// template argument deduction.
2425///
2426/// \param Info the argument will be updated to provide additional information
2427/// about template argument deduction.
2428///
2429/// \returns the result of template argument deduction.
2430Sema::TemplateDeductionResult
2431Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2432 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2433 FunctionDecl *&Specialization,
2434 TemplateDeductionInfo &Info) {
2435 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2436 QualType(), Specialization, Info);
2437}
2438
Douglas Gregor8a514912009-09-14 18:39:43 +00002439/// \brief Stores the result of comparing the qualifiers of two types.
2440enum DeductionQualifierComparison {
2441 NeitherMoreQualified = 0,
2442 ParamMoreQualified,
2443 ArgMoreQualified
2444};
2445
2446/// \brief Deduce the template arguments during partial ordering by comparing
2447/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2448///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002449/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002450///
2451/// \param TemplateParams the template parameters that we are deducing
2452///
2453/// \param ParamIn the parameter type
2454///
2455/// \param ArgIn the argument type
2456///
2457/// \param Info information about the template argument deduction itself
2458///
2459/// \param Deduced the deduced template arguments
2460///
2461/// \returns the result of template argument deduction so far. Note that a
2462/// "success" result means that template argument deduction has not yet failed,
2463/// but it may still fail, later, for other reasons.
2464static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002465DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002466 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002467 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002468 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002469 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2470 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002471 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2472 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002473
2474 // C++0x [temp.deduct.partial]p5:
2475 // Before the partial ordering is done, certain transformations are
2476 // performed on the types used for partial ordering:
2477 // - If P is a reference type, P is replaced by the type referred to.
2478 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002479 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002480 Param = ParamRef->getPointeeType();
2481
2482 // - If A is a reference type, A is replaced by the type referred to.
2483 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002484 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002485 Arg = ArgRef->getPointeeType();
2486
John McCalle27ec8a2009-10-23 23:03:21 +00002487 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002488 // C++0x [temp.deduct.partial]p6:
2489 // If both P and A were reference types (before being replaced with the
2490 // type referred to above), determine which of the two types (if any) is
2491 // more cv-qualified than the other; otherwise the types are considered to
2492 // be equally cv-qualified for partial ordering purposes. The result of this
2493 // determination will be used below.
2494 //
2495 // We save this information for later, using it only when deduction
2496 // succeeds in both directions.
2497 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2498 if (Param.isMoreQualifiedThan(Arg))
2499 QualifierResult = ParamMoreQualified;
2500 else if (Arg.isMoreQualifiedThan(Param))
2501 QualifierResult = ArgMoreQualified;
2502 QualifierComparisons->push_back(QualifierResult);
2503 }
2504
2505 // C++0x [temp.deduct.partial]p7:
2506 // Remove any top-level cv-qualifiers:
2507 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2508 // version of P.
2509 Param = Param.getUnqualifiedType();
2510 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2511 // version of A.
2512 Arg = Arg.getUnqualifiedType();
2513
2514 // C++0x [temp.deduct.partial]p8:
2515 // Using the resulting types P and A the deduction is then done as
2516 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2517 // from the argument template is considered to be at least as specialized
2518 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002519 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002520 Deduced, TDF_None);
2521}
2522
2523static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002524MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2525 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002526 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002527 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002528
2529/// \brief If this is a non-static member function,
2530static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2531 CXXMethodDecl *Method,
2532 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2533 if (Method->isStatic())
2534 return;
2535
2536 // C++ [over.match.funcs]p4:
2537 //
2538 // For non-static member functions, the type of the implicit
2539 // object parameter is
2540 // — "lvalue reference to cv X" for functions declared without a
2541 // ref-qualifier or with the & ref-qualifier
2542 // - "rvalue reference to cv X" for functions declared with the
2543 // && ref-qualifier
2544 //
2545 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2546 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2547 ArgTy = Context.getQualifiedType(ArgTy,
2548 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2549 ArgTy = Context.getLValueReferenceType(ArgTy);
2550 ArgTypes.push_back(ArgTy);
2551}
2552
Douglas Gregor8a514912009-09-14 18:39:43 +00002553/// \brief Determine whether the function template \p FT1 is at least as
2554/// specialized as \p FT2.
2555static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002556 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002557 FunctionTemplateDecl *FT1,
2558 FunctionTemplateDecl *FT2,
2559 TemplatePartialOrderingContext TPOC,
2560 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2561 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2562 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2563 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2564 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2565
2566 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2567 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002568 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002569 Deduced.resize(TemplateParams->size());
2570
2571 // C++0x [temp.deduct.partial]p3:
2572 // The types used to determine the ordering depend on the context in which
2573 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002574 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002575 CXXMethodDecl *Method1 = 0;
2576 CXXMethodDecl *Method2 = 0;
2577 bool IsNonStatic2 = false;
2578 bool IsNonStatic1 = false;
2579 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002580 switch (TPOC) {
2581 case TPOC_Call: {
2582 // - In the context of a function call, the function parameter types are
2583 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002584 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2585 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2586 IsNonStatic1 = Method1 && !Method1->isStatic();
2587 IsNonStatic2 = Method2 && !Method2->isStatic();
2588
2589 // C++0x [temp.func.order]p3:
2590 // [...] If only one of the function templates is a non-static
2591 // member, that function template is considered to have a new
2592 // first parameter inserted in its function parameter list. The
2593 // new parameter is of type "reference to cv A," where cv are
2594 // the cv-qualifiers of the function template (if any) and A is
2595 // the class of which the function template is a member.
2596 //
2597 // C++98/03 doesn't have this provision, so instead we drop the
2598 // first argument of the free function or static member, which
2599 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002600 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002601 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2602 IsNonStatic2 && !IsNonStatic1;
2603 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002604 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2605 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002606 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002607
2608 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002609 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2610 IsNonStatic1 && !IsNonStatic2;
2611 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002612 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2613 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002614 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002615
2616 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002617 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002618 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002619 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002620 Args2[I],
2621 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002622 Info,
2623 Deduced,
2624 QualifierComparisons))
2625 return false;
2626
2627 break;
2628 }
2629
2630 case TPOC_Conversion:
2631 // - In the context of a call to a conversion operator, the return types
2632 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002633 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002634 TemplateParams,
2635 Proto2->getResultType(),
2636 Proto1->getResultType(),
2637 Info,
2638 Deduced,
2639 QualifierComparisons))
2640 return false;
2641 break;
2642
2643 case TPOC_Other:
2644 // - In other contexts (14.6.6.2) the function template’s function type
2645 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002646 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002647 TemplateParams,
2648 FD2->getType(),
2649 FD1->getType(),
2650 Info,
2651 Deduced,
2652 QualifierComparisons))
2653 return false;
2654 break;
2655 }
2656
2657 // C++0x [temp.deduct.partial]p11:
2658 // In most cases, all template parameters must have values in order for
2659 // deduction to succeed, but for partial ordering purposes a template
2660 // parameter may remain without a value provided it is not used in the
2661 // types being used for partial ordering. [ Note: a template parameter used
2662 // in a non-deduced context is considered used. -end note]
2663 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2664 for (; ArgIdx != NumArgs; ++ArgIdx)
2665 if (Deduced[ArgIdx].isNull())
2666 break;
2667
2668 if (ArgIdx == NumArgs) {
2669 // All template arguments were deduced. FT1 is at least as specialized
2670 // as FT2.
2671 return true;
2672 }
2673
Douglas Gregore73bb602009-09-14 21:25:05 +00002674 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002675 llvm::SmallVector<bool, 4> UsedParameters;
2676 UsedParameters.resize(TemplateParams->size());
2677 switch (TPOC) {
2678 case TPOC_Call: {
2679 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002680 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2681 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2682 TemplateParams->getDepth(), UsedParameters);
2683 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002684 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2685 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002686 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002687 break;
2688 }
2689
2690 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002691 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2692 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002693 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002694 break;
2695
2696 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002697 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2698 TemplateParams->getDepth(),
2699 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002700 break;
2701 }
2702
2703 for (; ArgIdx != NumArgs; ++ArgIdx)
2704 // If this argument had no value deduced but was used in one of the types
2705 // used for partial ordering, then deduction fails.
2706 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2707 return false;
2708
2709 return true;
2710}
2711
2712
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002713/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002714/// to the rules of function template partial ordering (C++ [temp.func.order]).
2715///
2716/// \param FT1 the first function template
2717///
2718/// \param FT2 the second function template
2719///
Douglas Gregor8a514912009-09-14 18:39:43 +00002720/// \param TPOC the context in which we are performing partial ordering of
2721/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002722///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002723/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002724/// template is more specialized, returns NULL.
2725FunctionTemplateDecl *
2726Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2727 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002728 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002729 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002730 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002731 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2732 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002733 &QualifierComparisons);
2734
2735 if (Better1 != Better2) // We have a clear winner
2736 return Better1? FT1 : FT2;
2737
2738 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002739 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002740
2741
2742 // C++0x [temp.deduct.partial]p10:
2743 // If for each type being considered a given template is at least as
2744 // specialized for all types and more specialized for some set of types and
2745 // the other template is not more specialized for any types or is not at
2746 // least as specialized for any types, then the given template is more
2747 // specialized than the other template. Otherwise, neither template is more
2748 // specialized than the other.
2749 Better1 = false;
2750 Better2 = false;
2751 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2752 // C++0x [temp.deduct.partial]p9:
2753 // If, for a given type, deduction succeeds in both directions (i.e., the
2754 // types are identical after the transformations above) and if the type
2755 // from the argument template is more cv-qualified than the type from the
2756 // parameter template (as described above) that type is considered to be
2757 // more specialized than the other. If neither type is more cv-qualified
2758 // than the other then neither type is more specialized than the other.
2759 switch (QualifierComparisons[I]) {
2760 case NeitherMoreQualified:
2761 break;
2762
2763 case ParamMoreQualified:
2764 Better1 = true;
2765 if (Better2)
2766 return 0;
2767 break;
2768
2769 case ArgMoreQualified:
2770 Better2 = true;
2771 if (Better1)
2772 return 0;
2773 break;
2774 }
2775 }
2776
2777 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002778 if (Better1)
2779 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002780 else if (Better2)
2781 return FT2;
2782 else
2783 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002784}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002785
Douglas Gregord5a423b2009-09-25 18:43:00 +00002786/// \brief Determine if the two templates are equivalent.
2787static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2788 if (T1 == T2)
2789 return true;
2790
2791 if (!T1 || !T2)
2792 return false;
2793
2794 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2795}
2796
2797/// \brief Retrieve the most specialized of the given function template
2798/// specializations.
2799///
John McCallc373d482010-01-27 01:50:18 +00002800/// \param SpecBegin the start iterator of the function template
2801/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002802///
John McCallc373d482010-01-27 01:50:18 +00002803/// \param SpecEnd the end iterator of the function template
2804/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002805///
2806/// \param TPOC the partial ordering context to use to compare the function
2807/// template specializations.
2808///
2809/// \param Loc the location where the ambiguity or no-specializations
2810/// diagnostic should occur.
2811///
2812/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2813/// no matching candidates.
2814///
2815/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2816/// occurs.
2817///
2818/// \param CandidateDiag partial diagnostic used for each function template
2819/// specialization that is a candidate in the ambiguous ordering. One parameter
2820/// in this diagnostic should be unbound, which will correspond to the string
2821/// describing the template arguments for the function template specialization.
2822///
2823/// \param Index if non-NULL and the result of this function is non-nULL,
2824/// receives the index corresponding to the resulting function template
2825/// specialization.
2826///
2827/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002828/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002829///
2830/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2831/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002832UnresolvedSetIterator
2833Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2834 UnresolvedSetIterator SpecEnd,
2835 TemplatePartialOrderingContext TPOC,
2836 SourceLocation Loc,
2837 const PartialDiagnostic &NoneDiag,
2838 const PartialDiagnostic &AmbigDiag,
2839 const PartialDiagnostic &CandidateDiag) {
2840 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002841 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002842 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002843 }
2844
John McCallc373d482010-01-27 01:50:18 +00002845 if (SpecBegin + 1 == SpecEnd)
2846 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002847
2848 // Find the function template that is better than all of the templates it
2849 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002850 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002851 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002852 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002853 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002854 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2855 FunctionTemplateDecl *Challenger
2856 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002857 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002858 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002859 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002860 Challenger)) {
2861 Best = I;
2862 BestTemplate = Challenger;
2863 }
2864 }
2865
2866 // Make sure that the "best" function template is more specialized than all
2867 // of the others.
2868 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002869 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2870 FunctionTemplateDecl *Challenger
2871 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002872 if (I != Best &&
2873 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002874 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002875 BestTemplate)) {
2876 Ambiguous = true;
2877 break;
2878 }
2879 }
2880
2881 if (!Ambiguous) {
2882 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002883 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002884 }
2885
2886 // Diagnose the ambiguity.
2887 Diag(Loc, AmbigDiag);
2888
2889 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002890 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2891 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002892 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002893 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2894 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002895
John McCallc373d482010-01-27 01:50:18 +00002896 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002897}
2898
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002899/// \brief Returns the more specialized class template partial specialization
2900/// according to the rules of partial ordering of class template partial
2901/// specializations (C++ [temp.class.order]).
2902///
2903/// \param PS1 the first class template partial specialization
2904///
2905/// \param PS2 the second class template partial specialization
2906///
2907/// \returns the more specialized class template partial specialization. If
2908/// neither partial specialization is more specialized, returns NULL.
2909ClassTemplatePartialSpecializationDecl *
2910Sema::getMoreSpecializedPartialSpecialization(
2911 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002912 ClassTemplatePartialSpecializationDecl *PS2,
2913 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002914 // C++ [temp.class.order]p1:
2915 // For two class template partial specializations, the first is at least as
2916 // specialized as the second if, given the following rewrite to two
2917 // function templates, the first function template is at least as
2918 // specialized as the second according to the ordering rules for function
2919 // templates (14.6.6.2):
2920 // - the first function template has the same template parameters as the
2921 // first partial specialization and has a single function parameter
2922 // whose type is a class template specialization with the template
2923 // arguments of the first partial specialization, and
2924 // - the second function template has the same template parameters as the
2925 // second partial specialization and has a single function parameter
2926 // whose type is a class template specialization with the template
2927 // arguments of the second partial specialization.
2928 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002929 // Rather than synthesize function templates, we merely perform the
2930 // equivalent partial ordering by performing deduction directly on
2931 // the template arguments of the class template partial
2932 // specializations. This computation is slightly simpler than the
2933 // general problem of function template partial ordering, because
2934 // class template partial specializations are more constrained. We
2935 // know that every template parameter is deducible from the class
2936 // template partial specialization's template arguments, for
2937 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002938 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002939 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002940
2941 QualType PT1 = PS1->getInjectedSpecializationType();
2942 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002943
2944 // Determine whether PS1 is at least as specialized as PS2
2945 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002946 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002947 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002948 PT2,
2949 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002950 Info,
2951 Deduced,
2952 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002953 if (Better1) {
2954 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2955 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002956 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2957 PS1->getTemplateArgs(),
2958 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002959 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002960
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002961 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002962 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002963 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002964 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002965 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002966 PT1,
2967 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002968 Info,
2969 Deduced,
2970 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002971 if (Better2) {
2972 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2973 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002974 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2975 PS2->getTemplateArgs(),
2976 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002977 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002978
2979 if (Better1 == Better2)
2980 return 0;
2981
2982 return Better1? PS1 : PS2;
2983}
2984
Mike Stump1eb44332009-09-09 15:08:12 +00002985static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002986MarkUsedTemplateParameters(Sema &SemaRef,
2987 const TemplateArgument &TemplateArg,
2988 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002989 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002990 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002991
Douglas Gregore73bb602009-09-14 21:25:05 +00002992/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002993/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002994static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002995MarkUsedTemplateParameters(Sema &SemaRef,
2996 const Expr *E,
2997 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002998 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002999 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003000 // We can deduce from a pack expansion.
3001 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3002 E = Expansion->getPattern();
3003
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003004 // Skip through any implicit casts we added while type-checking.
3005 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3006 E = ICE->getSubExpr();
3007
Douglas Gregore73bb602009-09-14 21:25:05 +00003008 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3009 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003010 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003011 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003012 return;
3013
Mike Stump1eb44332009-09-09 15:08:12 +00003014 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003015 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3016 if (!NTTP)
3017 return;
3018
Douglas Gregored9c0f92009-10-29 00:04:11 +00003019 if (NTTP->getDepth() == Depth)
3020 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003021}
3022
Douglas Gregore73bb602009-09-14 21:25:05 +00003023/// \brief Mark the template parameters that are used by the given
3024/// nested name specifier.
3025static void
3026MarkUsedTemplateParameters(Sema &SemaRef,
3027 NestedNameSpecifier *NNS,
3028 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003029 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003030 llvm::SmallVectorImpl<bool> &Used) {
3031 if (!NNS)
3032 return;
3033
Douglas Gregored9c0f92009-10-29 00:04:11 +00003034 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3035 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003036 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003037 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003038}
3039
3040/// \brief Mark the template parameters that are used by the given
3041/// template name.
3042static void
3043MarkUsedTemplateParameters(Sema &SemaRef,
3044 TemplateName Name,
3045 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003046 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003047 llvm::SmallVectorImpl<bool> &Used) {
3048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3049 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003050 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3051 if (TTP->getDepth() == Depth)
3052 Used[TTP->getIndex()] = true;
3053 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003054 return;
3055 }
3056
Douglas Gregor788cd062009-11-11 01:00:40 +00003057 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3058 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3059 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003060 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003061 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3062 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003063}
3064
3065/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003066/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003067static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003068MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3069 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003070 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003071 llvm::SmallVectorImpl<bool> &Used) {
3072 if (T.isNull())
3073 return;
3074
Douglas Gregor031a5882009-06-13 00:26:55 +00003075 // Non-dependent types have nothing deducible
3076 if (!T->isDependentType())
3077 return;
3078
3079 T = SemaRef.Context.getCanonicalType(T);
3080 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003081 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003082 MarkUsedTemplateParameters(SemaRef,
3083 cast<PointerType>(T)->getPointeeType(),
3084 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003085 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003086 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003087 break;
3088
3089 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003090 MarkUsedTemplateParameters(SemaRef,
3091 cast<BlockPointerType>(T)->getPointeeType(),
3092 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003093 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003094 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003095 break;
3096
3097 case Type::LValueReference:
3098 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003099 MarkUsedTemplateParameters(SemaRef,
3100 cast<ReferenceType>(T)->getPointeeType(),
3101 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003102 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003103 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003104 break;
3105
3106 case Type::MemberPointer: {
3107 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003108 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003109 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003110 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003111 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003112 break;
3113 }
3114
3115 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003116 MarkUsedTemplateParameters(SemaRef,
3117 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003118 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003119 // Fall through to check the element type
3120
3121 case Type::ConstantArray:
3122 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003123 MarkUsedTemplateParameters(SemaRef,
3124 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003125 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003126 break;
3127
3128 case Type::Vector:
3129 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003130 MarkUsedTemplateParameters(SemaRef,
3131 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003132 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003133 break;
3134
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003135 case Type::DependentSizedExtVector: {
3136 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003137 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003138 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003139 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003140 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003141 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003142 break;
3143 }
3144
Douglas Gregor031a5882009-06-13 00:26:55 +00003145 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003146 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003147 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003148 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003149 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003150 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003151 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003152 break;
3153 }
3154
Douglas Gregored9c0f92009-10-29 00:04:11 +00003155 case Type::TemplateTypeParm: {
3156 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3157 if (TTP->getDepth() == Depth)
3158 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003159 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003160 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003161
John McCall31f17ec2010-04-27 00:57:59 +00003162 case Type::InjectedClassName:
3163 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3164 // fall through
3165
Douglas Gregor031a5882009-06-13 00:26:55 +00003166 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003167 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003168 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003169 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003170 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003171
3172 // C++0x [temp.deduct.type]p9:
3173 // If the template argument list of P contains a pack expansion that is not
3174 // the last template argument, the entire template argument list is a
3175 // non-deduced context.
3176 if (OnlyDeduced &&
3177 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3178 break;
3179
Douglas Gregore73bb602009-09-14 21:25:05 +00003180 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003181 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3182 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003183 break;
3184 }
3185
Douglas Gregore73bb602009-09-14 21:25:05 +00003186 case Type::Complex:
3187 if (!OnlyDeduced)
3188 MarkUsedTemplateParameters(SemaRef,
3189 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003190 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003191 break;
3192
Douglas Gregor4714c122010-03-31 17:34:00 +00003193 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003194 if (!OnlyDeduced)
3195 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003196 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003197 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003198 break;
3199
John McCall33500952010-06-11 00:33:02 +00003200 case Type::DependentTemplateSpecialization: {
3201 const DependentTemplateSpecializationType *Spec
3202 = cast<DependentTemplateSpecializationType>(T);
3203 if (!OnlyDeduced)
3204 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3205 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003206
3207 // C++0x [temp.deduct.type]p9:
3208 // If the template argument list of P contains a pack expansion that is not
3209 // the last template argument, the entire template argument list is a
3210 // non-deduced context.
3211 if (OnlyDeduced &&
3212 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3213 break;
3214
John McCall33500952010-06-11 00:33:02 +00003215 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3216 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3217 Used);
3218 break;
3219 }
3220
John McCallad5e7382010-03-01 23:49:17 +00003221 case Type::TypeOf:
3222 if (!OnlyDeduced)
3223 MarkUsedTemplateParameters(SemaRef,
3224 cast<TypeOfType>(T)->getUnderlyingType(),
3225 OnlyDeduced, Depth, Used);
3226 break;
3227
3228 case Type::TypeOfExpr:
3229 if (!OnlyDeduced)
3230 MarkUsedTemplateParameters(SemaRef,
3231 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3232 OnlyDeduced, Depth, Used);
3233 break;
3234
3235 case Type::Decltype:
3236 if (!OnlyDeduced)
3237 MarkUsedTemplateParameters(SemaRef,
3238 cast<DecltypeType>(T)->getUnderlyingExpr(),
3239 OnlyDeduced, Depth, Used);
3240 break;
3241
Douglas Gregor7536dd52010-12-20 02:24:11 +00003242 case Type::PackExpansion:
3243 MarkUsedTemplateParameters(SemaRef,
3244 cast<PackExpansionType>(T)->getPattern(),
3245 OnlyDeduced, Depth, Used);
3246 break;
3247
Douglas Gregore73bb602009-09-14 21:25:05 +00003248 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003249 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003250 case Type::VariableArray:
3251 case Type::FunctionNoProto:
3252 case Type::Record:
3253 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003254 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003255 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003256 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003257 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003258#define TYPE(Class, Base)
3259#define ABSTRACT_TYPE(Class, Base)
3260#define DEPENDENT_TYPE(Class, Base)
3261#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3262#include "clang/AST/TypeNodes.def"
3263 break;
3264 }
3265}
3266
Douglas Gregore73bb602009-09-14 21:25:05 +00003267/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003268/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003269static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003270MarkUsedTemplateParameters(Sema &SemaRef,
3271 const TemplateArgument &TemplateArg,
3272 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003273 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003274 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003275 switch (TemplateArg.getKind()) {
3276 case TemplateArgument::Null:
3277 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003278 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003279 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003280
Douglas Gregor031a5882009-06-13 00:26:55 +00003281 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003282 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003283 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003284 break;
3285
Douglas Gregor788cd062009-11-11 01:00:40 +00003286 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003287 case TemplateArgument::TemplateExpansion:
3288 MarkUsedTemplateParameters(SemaRef,
3289 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003290 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003291 break;
3292
3293 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003294 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003295 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003296 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003297
Anders Carlssond01b1da2009-06-15 17:04:53 +00003298 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003299 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3300 PEnd = TemplateArg.pack_end();
3301 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003302 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003303 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003304 }
3305}
3306
3307/// \brief Mark the template parameters can be deduced by the given
3308/// template argument list.
3309///
3310/// \param TemplateArgs the template argument list from which template
3311/// parameters will be deduced.
3312///
3313/// \param Deduced a bit vector whose elements will be set to \c true
3314/// to indicate when the corresponding template parameter will be
3315/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003316void
Douglas Gregore73bb602009-09-14 21:25:05 +00003317Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003318 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003319 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003320 // C++0x [temp.deduct.type]p9:
3321 // If the template argument list of P contains a pack expansion that is not
3322 // the last template argument, the entire template argument list is a
3323 // non-deduced context.
3324 if (OnlyDeduced &&
3325 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3326 return;
3327
Douglas Gregor031a5882009-06-13 00:26:55 +00003328 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003329 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3330 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003331}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003332
3333/// \brief Marks all of the template parameters that will be deduced by a
3334/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003335void
3336Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3337 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003338 TemplateParameterList *TemplateParams
3339 = FunctionTemplate->getTemplateParameters();
3340 Deduced.clear();
3341 Deduced.resize(TemplateParams->size());
3342
3343 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3344 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3345 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003346 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003347}