blob: 6d0db4a5413185b5a9c0b5f0587a956690649b1f [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 Gregor5c7bf422011-01-11 17:34:58 +000087/// \brief Stores the result of comparing the qualifiers of two types, used
88/// when
89enum DeductionQualifierComparison {
90 NeitherMoreQualified = 0,
91 ParamMoreQualified,
92 ArgMoreQualified
93};
94
95
Douglas Gregor20a55e22010-12-22 18:17:10 +000096static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000099 QualType Param,
100 QualType Arg,
101 TemplateDeductionInfo &Info,
102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000103 unsigned TDF,
104 bool PartialOrdering = false,
105 llvm::SmallVectorImpl<DeductionQualifierComparison> *
106 QualifierComparisons = 0);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000107
108static Sema::TemplateDeductionResult
109DeduceTemplateArguments(Sema &S,
110 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000111 const TemplateArgument *Params, unsigned NumParams,
112 const TemplateArgument *Args, unsigned NumArgs,
113 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000114 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
115 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000116
Douglas Gregor199d9912009-06-05 00:53:49 +0000117/// \brief If the given expression is of a form that permits the deduction
118/// of a non-type template parameter, return the declaration of that
119/// non-type template parameter.
120static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
121 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
122 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Douglas Gregor199d9912009-06-05 00:53:49 +0000124 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
125 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Douglas Gregor199d9912009-06-05 00:53:49 +0000127 return 0;
128}
129
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000130/// \brief Determine whether two declaration pointers refer to the same
131/// declaration.
132static bool isSameDeclaration(Decl *X, Decl *Y) {
133 if (!X || !Y)
134 return !X && !Y;
135
136 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
137 X = NX->getUnderlyingDecl();
138 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
139 Y = NY->getUnderlyingDecl();
140
141 return X->getCanonicalDecl() == Y->getCanonicalDecl();
142}
143
144/// \brief Verify that the given, deduced template arguments are compatible.
145///
146/// \returns The deduced template argument, or a NULL template argument if
147/// the deduced template arguments were incompatible.
148static DeducedTemplateArgument
149checkDeducedTemplateArguments(ASTContext &Context,
150 const DeducedTemplateArgument &X,
151 const DeducedTemplateArgument &Y) {
152 // We have no deduction for one or both of the arguments; they're compatible.
153 if (X.isNull())
154 return Y;
155 if (Y.isNull())
156 return X;
157
158 switch (X.getKind()) {
159 case TemplateArgument::Null:
160 llvm_unreachable("Non-deduced template arguments handled above");
161
162 case TemplateArgument::Type:
163 // If two template type arguments have the same type, they're compatible.
164 if (Y.getKind() == TemplateArgument::Type &&
165 Context.hasSameType(X.getAsType(), Y.getAsType()))
166 return X;
167
168 return DeducedTemplateArgument();
169
170 case TemplateArgument::Integral:
171 // If we deduced a constant in one case and either a dependent expression or
172 // declaration in another case, keep the integral constant.
173 // If both are integral constants with the same value, keep that value.
174 if (Y.getKind() == TemplateArgument::Expression ||
175 Y.getKind() == TemplateArgument::Declaration ||
176 (Y.getKind() == TemplateArgument::Integral &&
177 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
178 return DeducedTemplateArgument(X,
179 X.wasDeducedFromArrayBound() &&
180 Y.wasDeducedFromArrayBound());
181
182 // All other combinations are incompatible.
183 return DeducedTemplateArgument();
184
185 case TemplateArgument::Template:
186 if (Y.getKind() == TemplateArgument::Template &&
187 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
188 return X;
189
190 // All other combinations are incompatible.
191 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000192
193 case TemplateArgument::TemplateExpansion:
194 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
195 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
196 Y.getAsTemplateOrTemplatePattern()))
197 return X;
198
199 // All other combinations are incompatible.
200 return DeducedTemplateArgument();
201
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000202 case TemplateArgument::Expression:
203 // If we deduced a dependent expression in one case and either an integral
204 // constant or a declaration in another case, keep the integral constant
205 // or declaration.
206 if (Y.getKind() == TemplateArgument::Integral ||
207 Y.getKind() == TemplateArgument::Declaration)
208 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
209 Y.wasDeducedFromArrayBound());
210
211 if (Y.getKind() == TemplateArgument::Expression) {
212 // Compare the expressions for equality
213 llvm::FoldingSetNodeID ID1, ID2;
214 X.getAsExpr()->Profile(ID1, Context, true);
215 Y.getAsExpr()->Profile(ID2, Context, true);
216 if (ID1 == ID2)
217 return X;
218 }
219
220 // All other combinations are incompatible.
221 return DeducedTemplateArgument();
222
223 case TemplateArgument::Declaration:
224 // If we deduced a declaration and a dependent expression, keep the
225 // declaration.
226 if (Y.getKind() == TemplateArgument::Expression)
227 return X;
228
229 // If we deduced a declaration and an integral constant, keep the
230 // integral constant.
231 if (Y.getKind() == TemplateArgument::Integral)
232 return Y;
233
234 // If we deduced two declarations, make sure they they refer to the
235 // same declaration.
236 if (Y.getKind() == TemplateArgument::Declaration &&
237 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
238 return X;
239
240 // All other combinations are incompatible.
241 return DeducedTemplateArgument();
242
243 case TemplateArgument::Pack:
244 if (Y.getKind() != TemplateArgument::Pack ||
245 X.pack_size() != Y.pack_size())
246 return DeducedTemplateArgument();
247
248 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
249 XAEnd = X.pack_end(),
250 YA = Y.pack_begin();
251 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000252 if (checkDeducedTemplateArguments(Context,
253 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
254 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
255 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000256 return DeducedTemplateArgument();
257 }
258
259 return X;
260 }
261
262 return DeducedTemplateArgument();
263}
264
Mike Stump1eb44332009-09-09 15:08:12 +0000265/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000266/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000267static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000268DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000269 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000270 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000271 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000272 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000273 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000274 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000275 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000277 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
278 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
279 Deduced[NTTP->getIndex()],
280 NewDeduced);
281 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000282 Info.Param = NTTP;
283 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000284 Info.SecondArg = NewDeduced;
285 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000287
288 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000289 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000290}
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000293/// from the given type- or value-dependent expression.
294///
295/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000296static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000297DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000298 NonTypeTemplateParmDecl *NTTP,
299 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000300 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000301 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000302 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000303 "Cannot deduce non-type template argument with depth > 0");
304 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
305 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000307 DeducedTemplateArgument NewDeduced(Value);
308 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
309 Deduced[NTTP->getIndex()],
310 NewDeduced);
311
312 if (Result.isNull()) {
313 Info.Param = NTTP;
314 Info.FirstArg = Deduced[NTTP->getIndex()];
315 Info.SecondArg = NewDeduced;
316 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000317 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000318
319 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000320 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000321}
322
Douglas Gregor15755cb2009-11-13 23:45:44 +0000323/// \brief Deduce the value of the given non-type template parameter
324/// from the given declaration.
325///
326/// \returns true if deduction succeeded, false otherwise.
327static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000328DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000329 NonTypeTemplateParmDecl *NTTP,
330 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000331 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000332 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 assert(NTTP->getDepth() == 0 &&
334 "Cannot deduce non-type template argument with depth > 0");
335
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000336 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
337 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
338 Deduced[NTTP->getIndex()],
339 NewDeduced);
340 if (Result.isNull()) {
341 Info.Param = NTTP;
342 Info.FirstArg = Deduced[NTTP->getIndex()];
343 Info.SecondArg = NewDeduced;
344 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000345 }
346
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000347 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000348 return Sema::TDK_Success;
349}
350
Douglas Gregorf67875d2009-06-12 18:26:56 +0000351static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000352DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000353 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000354 TemplateName Param,
355 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000356 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000357 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000358 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000359 if (!ParamDecl) {
360 // The parameter type is dependent and is not a template template parameter,
361 // so there is nothing that we can deduce.
362 return Sema::TDK_Success;
363 }
364
365 if (TemplateTemplateParmDecl *TempParam
366 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000367 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
368 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
369 Deduced[TempParam->getIndex()],
370 NewDeduced);
371 if (Result.isNull()) {
372 Info.Param = TempParam;
373 Info.FirstArg = Deduced[TempParam->getIndex()];
374 Info.SecondArg = NewDeduced;
375 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000376 }
377
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000378 Deduced[TempParam->getIndex()] = Result;
379 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000380 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000381
382 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000384 return Sema::TDK_Success;
385
386 // Mismatch of non-dependent template parameter to argument.
387 Info.FirstArg = TemplateArgument(Param);
388 Info.SecondArg = TemplateArgument(Arg);
389 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000390}
391
Mike Stump1eb44332009-09-09 15:08:12 +0000392/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000393/// type (which is a template-id) with the template argument type.
394///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000395/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000396///
397/// \param TemplateParams the template parameters that we are deducing
398///
399/// \param Param the parameter type
400///
401/// \param Arg the argument type
402///
403/// \param Info information about the template argument deduction itself
404///
405/// \param Deduced the deduced template arguments
406///
407/// \returns the result of template argument deduction so far. Note that a
408/// "success" result means that template argument deduction has not yet failed,
409/// but it may still fail, later, for other reasons.
410static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000411DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000412 TemplateParameterList *TemplateParams,
413 const TemplateSpecializationType *Param,
414 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000415 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000416 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000417 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000420 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000421 = dyn_cast<TemplateSpecializationType>(Arg)) {
422 // Perform template argument deduction for the template name.
423 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000424 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000425 Param->getTemplateName(),
426 SpecArg->getTemplateName(),
427 Info, Deduced))
428 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000431 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000432 // argument. Ignore any missing/extra arguments, since they could be
433 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000434 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000435 Param->getArgs(), Param->getNumArgs(),
436 SpecArg->getArgs(), SpecArg->getNumArgs(),
437 Info, Deduced,
438 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // If the argument type is a class template specialization, we
442 // perform template argument deduction using its template
443 // arguments.
444 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
445 if (!RecordArg)
446 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
448 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000449 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
450 if (!SpecArg)
451 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000453 // Perform template argument deduction for the template name.
454 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000455 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000456 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000457 Param->getTemplateName(),
458 TemplateName(SpecArg->getSpecializedTemplate()),
459 Info, Deduced))
460 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor20a55e22010-12-22 18:17:10 +0000462 // Perform template argument deduction for the template arguments.
463 return DeduceTemplateArguments(S, TemplateParams,
464 Param->getArgs(), Param->getNumArgs(),
465 SpecArg->getTemplateArgs().data(),
466 SpecArg->getTemplateArgs().size(),
467 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000468}
469
John McCallcd05e812010-08-28 22:14:41 +0000470/// \brief Determines whether the given type is an opaque type that
471/// might be more qualified when instantiated.
472static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
473 switch (T->getTypeClass()) {
474 case Type::TypeOfExpr:
475 case Type::TypeOf:
476 case Type::DependentName:
477 case Type::Decltype:
478 case Type::UnresolvedUsing:
479 return true;
480
481 case Type::ConstantArray:
482 case Type::IncompleteArray:
483 case Type::VariableArray:
484 case Type::DependentSizedArray:
485 return IsPossiblyOpaquelyQualifiedType(
486 cast<ArrayType>(T)->getElementType());
487
488 default:
489 return false;
490 }
491}
492
Douglas Gregord3731192011-01-10 07:32:04 +0000493/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000494static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000495getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000496 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
497 return std::make_pair(TTP->getDepth(), TTP->getIndex());
498
499 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
500 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
501
502 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
503 return std::make_pair(TTP->getDepth(), TTP->getIndex());
504}
505
Douglas Gregord3731192011-01-10 07:32:04 +0000506/// \brief Retrieve the depth and index of an unexpanded parameter pack.
507static std::pair<unsigned, unsigned>
508getDepthAndIndex(UnexpandedParameterPack UPP) {
509 if (const TemplateTypeParmType *TTP
510 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
511 return std::make_pair(TTP->getDepth(), TTP->getIndex());
512
513 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
514}
515
Douglas Gregor603cfb42011-01-05 23:12:31 +0000516/// \brief Helper function to build a TemplateParameter when we don't
517/// know its type statically.
518static TemplateParameter makeTemplateParameter(Decl *D) {
519 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
520 return TemplateParameter(TTP);
521 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
522 return TemplateParameter(NTTP);
523
524 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
525}
526
Douglas Gregor54293852011-01-10 17:35:05 +0000527/// \brief Prepare to perform template argument deduction for all of the
528/// arguments in a set of argument packs.
529static void PrepareArgumentPackDeduction(Sema &S,
530 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
531 const llvm::SmallVectorImpl<unsigned> &PackIndices,
532 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
533 llvm::SmallVectorImpl<
534 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
535 // Save the deduced template arguments for each parameter pack expanded
536 // by this pack expansion, then clear out the deduction.
537 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
538 // Save the previously-deduced argument pack, then clear it out so that we
539 // can deduce a new argument pack.
540 SavedPacks[I] = Deduced[PackIndices[I]];
541 Deduced[PackIndices[I]] = TemplateArgument();
542
543 // If the template arugment pack was explicitly specified, add that to
544 // the set of deduced arguments.
545 const TemplateArgument *ExplicitArgs;
546 unsigned NumExplicitArgs;
547 if (NamedDecl *PartiallySubstitutedPack
548 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
549 &ExplicitArgs,
550 &NumExplicitArgs)) {
551 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
552 NewlyDeducedPacks[I].append(ExplicitArgs,
553 ExplicitArgs + NumExplicitArgs);
554 }
555 }
556}
557
Douglas Gregor0216f812011-01-10 17:53:52 +0000558/// \brief Finish template argument deduction for a set of argument packs,
559/// producing the argument packs and checking for consistency with prior
560/// deductions.
561static Sema::TemplateDeductionResult
562FinishArgumentPackDeduction(Sema &S,
563 TemplateParameterList *TemplateParams,
564 bool HasAnyArguments,
565 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
566 const llvm::SmallVectorImpl<unsigned> &PackIndices,
567 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
568 llvm::SmallVectorImpl<
569 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
570 TemplateDeductionInfo &Info) {
571 // Build argument packs for each of the parameter packs expanded by this
572 // pack expansion.
573 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
574 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
575 // We were not able to deduce anything for this parameter pack,
576 // so just restore the saved argument pack.
577 Deduced[PackIndices[I]] = SavedPacks[I];
578 continue;
579 }
580
581 DeducedTemplateArgument NewPack;
582
583 if (NewlyDeducedPacks[I].empty()) {
584 // If we deduced an empty argument pack, create it now.
585 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
586 } else {
587 TemplateArgument *ArgumentPack
588 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
589 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
590 ArgumentPack);
591 NewPack
592 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
593 NewlyDeducedPacks[I].size()),
594 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
595 }
596
597 DeducedTemplateArgument Result
598 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
599 if (Result.isNull()) {
600 Info.Param
601 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
602 Info.FirstArg = SavedPacks[I];
603 Info.SecondArg = NewPack;
604 return Sema::TDK_Inconsistent;
605 }
606
607 Deduced[PackIndices[I]] = Result;
608 }
609
610 return Sema::TDK_Success;
611}
612
Douglas Gregor603cfb42011-01-05 23:12:31 +0000613/// \brief Deduce the template arguments by comparing the list of parameter
614/// types to the list of argument types, as in the parameter-type-lists of
615/// function types (C++ [temp.deduct.type]p10).
616///
617/// \param S The semantic analysis object within which we are deducing
618///
619/// \param TemplateParams The template parameters that we are deducing
620///
621/// \param Params The list of parameter types
622///
623/// \param NumParams The number of types in \c Params
624///
625/// \param Args The list of argument types
626///
627/// \param NumArgs The number of types in \c Args
628///
629/// \param Info information about the template argument deduction itself
630///
631/// \param Deduced the deduced template arguments
632///
633/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
634/// how template argument deduction is performed.
635///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000636/// \param PartialOrdering If true, we are performing template argument
637/// deduction for during partial ordering for a call
638/// (C++0x [temp.deduct.partial]).
639///
640/// \param QualifierComparisons If we're performing template argument deduction
641/// in the context of partial ordering, the set of qualifier comparisons.
642///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000643/// \returns the result of template argument deduction so far. Note that a
644/// "success" result means that template argument deduction has not yet failed,
645/// but it may still fail, later, for other reasons.
646static Sema::TemplateDeductionResult
647DeduceTemplateArguments(Sema &S,
648 TemplateParameterList *TemplateParams,
649 const QualType *Params, unsigned NumParams,
650 const QualType *Args, unsigned NumArgs,
651 TemplateDeductionInfo &Info,
652 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000653 unsigned TDF,
654 bool PartialOrdering = false,
655 llvm::SmallVectorImpl<DeductionQualifierComparison> *
656 QualifierComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000657 // Fast-path check to see if we have too many/too few arguments.
658 if (NumParams != NumArgs &&
659 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
660 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000661 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000662
663 // C++0x [temp.deduct.type]p10:
664 // Similarly, if P has a form that contains (T), then each parameter type
665 // Pi of the respective parameter-type- list of P is compared with the
666 // corresponding parameter type Ai of the corresponding parameter-type-list
667 // of A. [...]
668 unsigned ArgIdx = 0, ParamIdx = 0;
669 for (; ParamIdx != NumParams; ++ParamIdx) {
670 // Check argument types.
671 const PackExpansionType *Expansion
672 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
673 if (!Expansion) {
674 // Simple case: compare the parameter and argument types at this point.
675
676 // Make sure we have an argument.
677 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000678 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000679
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000680
Douglas Gregor603cfb42011-01-05 23:12:31 +0000681 if (Sema::TemplateDeductionResult Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000682 = DeduceTemplateArguments(S, TemplateParams,
683 Params[ParamIdx],
684 Args[ArgIdx],
685 Info, Deduced, TDF,
686 PartialOrdering,
687 QualifierComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000688 return Result;
689
690 ++ArgIdx;
691 continue;
692 }
693
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000694 // C++0x [temp.deduct.type]p5:
695 // The non-deduced contexts are:
696 // - A function parameter pack that does not occur at the end of the
697 // parameter-declaration-clause.
698 if (ParamIdx + 1 < NumParams)
699 return Sema::TDK_Success;
700
Douglas Gregor603cfb42011-01-05 23:12:31 +0000701 // C++0x [temp.deduct.type]p10:
702 // If the parameter-declaration corresponding to Pi is a function
703 // parameter pack, then the type of its declarator- id is compared with
704 // each remaining parameter type in the parameter-type-list of A. Each
705 // comparison deduces template arguments for subsequent positions in the
706 // template parameter packs expanded by the function parameter pack.
707
708 // Compute the set of template parameter indices that correspond to
709 // parameter packs expanded by the pack expansion.
710 llvm::SmallVector<unsigned, 2> PackIndices;
711 QualType Pattern = Expansion->getPattern();
712 {
713 llvm::BitVector SawIndices(TemplateParams->size());
714 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
715 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
716 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
717 unsigned Depth, Index;
718 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
719 if (Depth == 0 && !SawIndices[Index]) {
720 SawIndices[Index] = true;
721 PackIndices.push_back(Index);
722 }
723 }
724 }
725 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
726
Douglas Gregord3731192011-01-10 07:32:04 +0000727 // Keep track of the deduced template arguments for each parameter pack
728 // expanded by this pack expansion (the outer index) and for each
729 // template argument (the inner SmallVectors).
730 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
731 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000732 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000733 SavedPacks(PackIndices.size());
734 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
735 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000736
Douglas Gregor603cfb42011-01-05 23:12:31 +0000737 bool HasAnyArguments = false;
738 for (; ArgIdx < NumArgs; ++ArgIdx) {
739 HasAnyArguments = true;
740
741 // Deduce template arguments from the pattern.
742 if (Sema::TemplateDeductionResult Result
743 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000744 Info, Deduced, PartialOrdering,
745 QualifierComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000746 return Result;
747
748 // Capture the deduced template arguments for each parameter pack expanded
749 // by this pack expansion, add them to the list of arguments we've deduced
750 // for that pack, then clear out the deduced argument.
751 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
752 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
753 if (!DeducedArg.isNull()) {
754 NewlyDeducedPacks[I].push_back(DeducedArg);
755 DeducedArg = DeducedTemplateArgument();
756 }
757 }
758 }
759
760 // Build argument packs for each of the parameter packs expanded by this
761 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000762 if (Sema::TemplateDeductionResult Result
763 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
764 Deduced, PackIndices, SavedPacks,
765 NewlyDeducedPacks, Info))
766 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000767 }
768
769 // Make sure we don't have any extra arguments.
770 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000771 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000772
773 return Sema::TDK_Success;
774}
775
Douglas Gregor500d3312009-06-26 18:27:22 +0000776/// \brief Deduce the template arguments by comparing the parameter type and
777/// the argument type (C++ [temp.deduct.type]).
778///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000779/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000780///
781/// \param TemplateParams the template parameters that we are deducing
782///
783/// \param ParamIn the parameter type
784///
785/// \param ArgIn the argument type
786///
787/// \param Info information about the template argument deduction itself
788///
789/// \param Deduced the deduced template arguments
790///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000791/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000792/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000793///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000794/// \param PartialOrdering Whether we're performing template argument deduction
795/// in the context of partial ordering (C++0x [temp.deduct.partial]).
796///
797/// \param QualifierComparisons If we're performing template argument deduction
798/// in the context of partial ordering, the set of qualifier comparisons.
799///
Douglas Gregor500d3312009-06-26 18:27:22 +0000800/// \returns the result of template argument deduction so far. Note that a
801/// "success" result means that template argument deduction has not yet failed,
802/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000803static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000804DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000805 TemplateParameterList *TemplateParams,
806 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000807 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000808 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000809 unsigned TDF,
810 bool PartialOrdering,
811 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000812 // We only want to look at the canonical types, since typedefs and
813 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000814 QualType Param = S.Context.getCanonicalType(ParamIn);
815 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000816
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000817 if (PartialOrdering) {
818 // C++0x [temp.deduct.partial]p5:
819 // Before the partial ordering is done, certain transformations are
820 // performed on the types used for partial ordering:
821 // - If P is a reference type, P is replaced by the type referred to.
822 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
823 if (ParamRef)
824 Param = ParamRef->getPointeeType();
825
826 // - If A is a reference type, A is replaced by the type referred to.
827 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
828 if (ArgRef)
829 Arg = ArgRef->getPointeeType();
830
831 if (QualifierComparisons && ParamRef && ArgRef) {
832 // C++0x [temp.deduct.partial]p6:
833 // If both P and A were reference types (before being replaced with the
834 // type referred to above), determine which of the two types (if any) is
835 // more cv-qualified than the other; otherwise the types are considered
836 // to be equally cv-qualified for partial ordering purposes. The result
837 // of this determination will be used below.
838 //
839 // We save this information for later, using it only when deduction
840 // succeeds in both directions.
841 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
842 if (Param.isMoreQualifiedThan(Arg))
843 QualifierResult = ParamMoreQualified;
844 else if (Arg.isMoreQualifiedThan(Param))
845 QualifierResult = ArgMoreQualified;
846 QualifierComparisons->push_back(QualifierResult);
847 }
848
849 // C++0x [temp.deduct.partial]p7:
850 // Remove any top-level cv-qualifiers:
851 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
852 // version of P.
853 Param = Param.getUnqualifiedType();
854 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
855 // version of A.
856 Arg = Arg.getUnqualifiedType();
857 } else {
858 // C++0x [temp.deduct.call]p4 bullet 1:
859 // - If the original P is a reference type, the deduced A (i.e., the type
860 // referred to by the reference) can be more cv-qualified than the
861 // transformed A.
862 if (TDF & TDF_ParamWithReferenceType) {
863 Qualifiers Quals;
864 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
865 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
866 Arg.getCVRQualifiersThroughArrayTypes());
867 Param = S.Context.getQualifiedType(UnqualParam, Quals);
868 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000869 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000870
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000871 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000872 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000873 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000874 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000875
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000876 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000877 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000878
Douglas Gregor199d9912009-06-05 00:53:49 +0000879 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000880 // A template type argument T, a template template argument TT or a
881 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000882 // the following forms:
883 //
884 // T
885 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000886 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000887 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000888 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000889 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000891 // If the argument type is an array type, move the qualifiers up to the
892 // top level, so they can be matched with the qualifiers on the parameter.
893 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000894 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000895 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000896 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000897 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000899 RecanonicalizeArg = true;
900 }
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000903 // The argument type can not be less qualified than the parameter
904 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000905 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000906 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000907 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000908 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000909 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000910 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000911
912 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000913 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000914 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000915
916 // local manipulation is okay because it's canonical
917 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000918 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000919 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000921 DeducedTemplateArgument NewDeduced(DeducedType);
922 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
923 Deduced[Index],
924 NewDeduced);
925 if (Result.isNull()) {
926 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
927 Info.FirstArg = Deduced[Index];
928 Info.SecondArg = NewDeduced;
929 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000930 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000931
932 Deduced[Index] = Result;
933 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000934 }
935
Douglas Gregorf67875d2009-06-12 18:26:56 +0000936 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000937 Info.FirstArg = TemplateArgument(ParamIn);
938 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000939
Douglas Gregor508f1c82009-06-26 23:10:12 +0000940 // Check the cv-qualifiers on the parameter and argument types.
941 if (!(TDF & TDF_IgnoreQualifiers)) {
942 if (TDF & TDF_ParamWithReferenceType) {
943 if (Param.isMoreQualifiedThan(Arg))
944 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000945 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000946 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000947 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000948 }
949 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000950
Douglas Gregord560d502009-06-04 00:21:18 +0000951 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000952 // No deduction possible for these types
953 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000954 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregor199d9912009-06-05 00:53:49 +0000956 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000957 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000958 QualType PointeeType;
959 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
960 PointeeType = PointerArg->getPointeeType();
961 } else if (const ObjCObjectPointerType *PointerArg
962 = Arg->getAs<ObjCObjectPointerType>()) {
963 PointeeType = PointerArg->getPointeeType();
964 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Douglas Gregor41128772009-06-26 23:27:24 +0000968 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000969 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000970 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000971 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000972 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Douglas Gregor199d9912009-06-05 00:53:49 +0000975 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000976 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000977 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000978 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000979 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000981 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000982 cast<LValueReferenceType>(Param)->getPointeeType(),
983 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000984 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000985 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000986
Douglas Gregor199d9912009-06-05 00:53:49 +0000987 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000988 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000989 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000990 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000991 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000993 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000994 cast<RValueReferenceType>(Param)->getPointeeType(),
995 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000996 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Douglas Gregor199d9912009-06-05 00:53:49 +0000999 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001000 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001001 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001002 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001003 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001004 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001005
John McCalle4f26e52010-08-19 00:20:19 +00001006 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001007 return DeduceTemplateArguments(S, TemplateParams,
1008 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001009 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001010 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001011 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001012
1013 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001014 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001015 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001016 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001017 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001018 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
1020 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001021 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001022 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001023 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001024
John McCalle4f26e52010-08-19 00:20:19 +00001025 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001026 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001027 ConstantArrayParm->getElementType(),
1028 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001029 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001030 }
1031
Douglas Gregor199d9912009-06-05 00:53:49 +00001032 // type [i]
1033 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001034 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001035 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001036 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCalle4f26e52010-08-19 00:20:19 +00001038 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1039
Douglas Gregor199d9912009-06-05 00:53:49 +00001040 // Check the element type of the arrays
1041 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001042 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001043 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001044 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001045 DependentArrayParm->getElementType(),
1046 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001047 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001048 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Douglas Gregor199d9912009-06-05 00:53:49 +00001050 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001051 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001052 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1053 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001054 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001055
1056 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001057 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001059 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001060 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001061 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1062 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001063 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1064 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001065 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001066 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001067 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001068 if (const DependentSizedArrayType *DependentArrayArg
1069 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001070 if (DependentArrayArg->getSizeExpr())
1071 return DeduceNonTypeTemplateArgument(S, NTTP,
1072 DependentArrayArg->getSizeExpr(),
1073 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Douglas Gregor199d9912009-06-05 00:53:49 +00001075 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001076 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
1079 // type(*)(T)
1080 // T(*)()
1081 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001082 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001083 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001084 dyn_cast<FunctionProtoType>(Arg);
1085 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001086 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
1088 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001089 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001090
Mike Stump1eb44332009-09-09 15:08:12 +00001091 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001092 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001093 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001095 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001096 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001097
Anders Carlssona27fad52009-06-08 15:19:08 +00001098 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001099 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001100 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001101 FunctionProtoParam->getResultType(),
1102 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001103 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001104 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Douglas Gregor603cfb42011-01-05 23:12:31 +00001106 return DeduceTemplateArguments(S, TemplateParams,
1107 FunctionProtoParam->arg_type_begin(),
1108 FunctionProtoParam->getNumArgs(),
1109 FunctionProtoArg->arg_type_begin(),
1110 FunctionProtoArg->getNumArgs(),
1111 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001112 }
Mike Stump1eb44332009-09-09 15:08:12 +00001113
John McCall3cb0ebd2010-03-10 03:28:59 +00001114 case Type::InjectedClassName: {
1115 // Treat a template's injected-class-name as if the template
1116 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001117 Param = cast<InjectedClassNameType>(Param)
1118 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001119 assert(isa<TemplateSpecializationType>(Param) &&
1120 "injected class name is not a template specialization type");
1121 // fall through
1122 }
1123
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001124 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001125 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001126 // TT<T>
1127 // TT<i>
1128 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001129 case Type::TemplateSpecialization: {
1130 const TemplateSpecializationType *SpecParam
1131 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001133 // Try to deduce template arguments from the template-id.
1134 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001135 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001136 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001138 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001139 // C++ [temp.deduct.call]p3b3:
1140 // If P is a class, and P has the form template-id, then A can be a
1141 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001142 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001143 // class pointed to by the deduced A.
1144 //
1145 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001146 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001147 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001148 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1149 // We cannot inspect base classes as part of deduction when the type
1150 // is incomplete, so either instantiate any templates necessary to
1151 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001152 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001153 return Result;
1154
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001155 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001156 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001157 // ToVisit is our stack of records that we still need to visit.
1158 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1159 llvm::SmallVector<const RecordType *, 8> ToVisit;
1160 ToVisit.push_back(RecordT);
1161 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001162 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1163 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001164 while (!ToVisit.empty()) {
1165 // Retrieve the next class in the inheritance hierarchy.
1166 const RecordType *NextT = ToVisit.back();
1167 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001169 // If we have already seen this type, skip it.
1170 if (!Visited.insert(NextT))
1171 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001173 // If this is a base class, try to perform template argument
1174 // deduction from it.
1175 if (NextT != RecordT) {
1176 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001177 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001178 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001180 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001181 // note that we had some success. Otherwise, ignore any deductions
1182 // from this base class.
1183 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001184 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001185 DeducedOrig = Deduced;
1186 }
1187 else
1188 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001191 // Visit base classes
1192 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1193 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1194 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001195 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001196 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001197 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001198 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001199 }
1200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001202 if (Successful)
1203 return Sema::TDK_Success;
1204 }
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001208 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001209 }
1210
Douglas Gregor637a4092009-06-10 23:47:09 +00001211 // T type::*
1212 // T T::*
1213 // T (type::*)()
1214 // type (T::*)()
1215 // type (type::*)(T)
1216 // type (T::*)(T)
1217 // T (type::*)(T)
1218 // T (T::*)()
1219 // T (T::*)(T)
1220 case Type::MemberPointer: {
1221 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1222 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1223 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001224 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001225
Douglas Gregorf67875d2009-06-12 18:26:56 +00001226 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001227 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001228 MemPtrParam->getPointeeType(),
1229 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001230 Info, Deduced,
1231 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001232 return Result;
1233
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001234 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001235 QualType(MemPtrParam->getClass(), 0),
1236 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001237 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001238 }
1239
Anders Carlsson9a917e42009-06-12 22:56:54 +00001240 // (clang extension)
1241 //
Mike Stump1eb44332009-09-09 15:08:12 +00001242 // type(^)(T)
1243 // T(^)()
1244 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001245 case Type::BlockPointer: {
1246 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1247 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Anders Carlsson859ba502009-06-12 16:23:10 +00001249 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001250 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001252 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001253 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001254 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001255 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001256 }
1257
Douglas Gregor637a4092009-06-10 23:47:09 +00001258 case Type::TypeOfExpr:
1259 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001260 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001261 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001262 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001263
Douglas Gregord560d502009-06-04 00:21:18 +00001264 default:
1265 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001266 }
1267
1268 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001269 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001270}
1271
Douglas Gregorf67875d2009-06-12 18:26:56 +00001272static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001273DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001274 TemplateParameterList *TemplateParams,
1275 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001276 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001277 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001278 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001279 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001280 case TemplateArgument::Null:
1281 assert(false && "Null template argument in parameter list");
1282 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001283
1284 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001285 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001286 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001287 Arg.getAsType(), Info, Deduced, 0);
1288 Info.FirstArg = Param;
1289 Info.SecondArg = Arg;
1290 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001291
Douglas Gregor788cd062009-11-11 01:00:40 +00001292 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001293 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001294 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001295 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001296 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001297 Info.FirstArg = Param;
1298 Info.SecondArg = Arg;
1299 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001300
1301 case TemplateArgument::TemplateExpansion:
1302 llvm_unreachable("caller should handle pack expansions");
1303 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001304
Douglas Gregor199d9912009-06-05 00:53:49 +00001305 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001306 if (Arg.getKind() == TemplateArgument::Declaration &&
1307 Param.getAsDecl()->getCanonicalDecl() ==
1308 Arg.getAsDecl()->getCanonicalDecl())
1309 return Sema::TDK_Success;
1310
Douglas Gregorf67875d2009-06-12 18:26:56 +00001311 Info.FirstArg = Param;
1312 Info.SecondArg = Arg;
1313 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Douglas Gregor199d9912009-06-05 00:53:49 +00001315 case TemplateArgument::Integral:
1316 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001317 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001318 return Sema::TDK_Success;
1319
1320 Info.FirstArg = Param;
1321 Info.SecondArg = Arg;
1322 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001323 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001324
1325 if (Arg.getKind() == TemplateArgument::Expression) {
1326 Info.FirstArg = Param;
1327 Info.SecondArg = Arg;
1328 return Sema::TDK_NonDeducedMismatch;
1329 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001330
Douglas Gregorf67875d2009-06-12 18:26:56 +00001331 Info.FirstArg = Param;
1332 Info.SecondArg = Arg;
1333 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Douglas Gregor199d9912009-06-05 00:53:49 +00001335 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001336 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001337 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1338 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001339 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001340 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001341 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001342 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001343 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001344 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001345 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001346 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001347 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001348 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001349 Info, Deduced);
1350
Douglas Gregorf67875d2009-06-12 18:26:56 +00001351 Info.FirstArg = Param;
1352 Info.SecondArg = Arg;
1353 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Douglas Gregor199d9912009-06-05 00:53:49 +00001356 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001357 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001358 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001359 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001360 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001361 }
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Douglas Gregorf67875d2009-06-12 18:26:56 +00001363 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001364}
1365
Douglas Gregor20a55e22010-12-22 18:17:10 +00001366/// \brief Determine whether there is a template argument to be used for
1367/// deduction.
1368///
1369/// This routine "expands" argument packs in-place, overriding its input
1370/// parameters so that \c Args[ArgIdx] will be the available template argument.
1371///
1372/// \returns true if there is another template argument (which will be at
1373/// \c Args[ArgIdx]), false otherwise.
1374static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1375 unsigned &ArgIdx,
1376 unsigned &NumArgs) {
1377 if (ArgIdx == NumArgs)
1378 return false;
1379
1380 const TemplateArgument &Arg = Args[ArgIdx];
1381 if (Arg.getKind() != TemplateArgument::Pack)
1382 return true;
1383
1384 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1385 Args = Arg.pack_begin();
1386 NumArgs = Arg.pack_size();
1387 ArgIdx = 0;
1388 return ArgIdx < NumArgs;
1389}
1390
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001391/// \brief Determine whether the given set of template arguments has a pack
1392/// expansion that is not the last template argument.
1393static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1394 unsigned NumArgs) {
1395 unsigned ArgIdx = 0;
1396 while (ArgIdx < NumArgs) {
1397 const TemplateArgument &Arg = Args[ArgIdx];
1398
1399 // Unwrap argument packs.
1400 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1401 Args = Arg.pack_begin();
1402 NumArgs = Arg.pack_size();
1403 ArgIdx = 0;
1404 continue;
1405 }
1406
1407 ++ArgIdx;
1408 if (ArgIdx == NumArgs)
1409 return false;
1410
1411 if (Arg.isPackExpansion())
1412 return true;
1413 }
1414
1415 return false;
1416}
1417
Douglas Gregor20a55e22010-12-22 18:17:10 +00001418static Sema::TemplateDeductionResult
1419DeduceTemplateArguments(Sema &S,
1420 TemplateParameterList *TemplateParams,
1421 const TemplateArgument *Params, unsigned NumParams,
1422 const TemplateArgument *Args, unsigned NumArgs,
1423 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001424 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1425 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001426 // C++0x [temp.deduct.type]p9:
1427 // If the template argument list of P contains a pack expansion that is not
1428 // the last template argument, the entire template argument list is a
1429 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001430 if (hasPackExpansionBeforeEnd(Params, NumParams))
1431 return Sema::TDK_Success;
1432
Douglas Gregore02e2622010-12-22 21:19:48 +00001433 // C++0x [temp.deduct.type]p9:
1434 // If P has a form that contains <T> or <i>, then each argument Pi of the
1435 // respective template argument list P is compared with the corresponding
1436 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001437 unsigned ArgIdx = 0, ParamIdx = 0;
1438 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1439 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001440 // FIXME: Variadic templates.
1441 // What do we do if the argument is a pack expansion?
1442
Douglas Gregor20a55e22010-12-22 18:17:10 +00001443 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001444 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001445
1446 // Check whether we have enough arguments.
1447 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001448 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001449 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001450
Douglas Gregore02e2622010-12-22 21:19:48 +00001451 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001452 if (Sema::TemplateDeductionResult Result
1453 = DeduceTemplateArguments(S, TemplateParams,
1454 Params[ParamIdx], Args[ArgIdx],
1455 Info, Deduced))
1456 return Result;
1457
1458 // Move to the next argument.
1459 ++ArgIdx;
1460 continue;
1461 }
1462
Douglas Gregore02e2622010-12-22 21:19:48 +00001463 // The parameter is a pack expansion.
1464
1465 // C++0x [temp.deduct.type]p9:
1466 // If Pi is a pack expansion, then the pattern of Pi is compared with
1467 // each remaining argument in the template argument list of A. Each
1468 // comparison deduces template arguments for subsequent positions in the
1469 // template parameter packs expanded by Pi.
1470 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1471
1472 // Compute the set of template parameter indices that correspond to
1473 // parameter packs expanded by the pack expansion.
1474 llvm::SmallVector<unsigned, 2> PackIndices;
1475 {
1476 llvm::BitVector SawIndices(TemplateParams->size());
1477 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1478 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1479 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1480 unsigned Depth, Index;
1481 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1482 if (Depth == 0 && !SawIndices[Index]) {
1483 SawIndices[Index] = true;
1484 PackIndices.push_back(Index);
1485 }
1486 }
1487 }
1488 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1489
1490 // FIXME: If there are no remaining arguments, we can bail out early
1491 // and set any deduced parameter packs to an empty argument pack.
1492 // The latter part of this is a (minor) correctness issue.
1493
1494 // Save the deduced template arguments for each parameter pack expanded
1495 // by this pack expansion, then clear out the deduction.
1496 llvm::SmallVector<DeducedTemplateArgument, 2>
1497 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001498 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1499 NewlyDeducedPacks(PackIndices.size());
1500 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1501 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001502
1503 // Keep track of the deduced template arguments for each parameter pack
1504 // expanded by this pack expansion (the outer index) and for each
1505 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001506 bool HasAnyArguments = false;
1507 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1508 HasAnyArguments = true;
1509
1510 // Deduce template arguments from the pattern.
1511 if (Sema::TemplateDeductionResult Result
1512 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1513 Info, Deduced))
1514 return Result;
1515
1516 // Capture the deduced template arguments for each parameter pack expanded
1517 // by this pack expansion, add them to the list of arguments we've deduced
1518 // for that pack, then clear out the deduced argument.
1519 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1520 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1521 if (!DeducedArg.isNull()) {
1522 NewlyDeducedPacks[I].push_back(DeducedArg);
1523 DeducedArg = DeducedTemplateArgument();
1524 }
1525 }
1526
1527 ++ArgIdx;
1528 }
1529
1530 // Build argument packs for each of the parameter packs expanded by this
1531 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001532 if (Sema::TemplateDeductionResult Result
1533 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1534 Deduced, PackIndices, SavedPacks,
1535 NewlyDeducedPacks, Info))
1536 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001537 }
1538
1539 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001540 if (NumberOfArgumentsMustMatch &&
1541 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001542 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001543
1544 return Sema::TDK_Success;
1545}
1546
Mike Stump1eb44332009-09-09 15:08:12 +00001547static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001548DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001549 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001550 const TemplateArgumentList &ParamList,
1551 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001552 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001553 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001554 return DeduceTemplateArguments(S, TemplateParams,
1555 ParamList.data(), ParamList.size(),
1556 ArgList.data(), ArgList.size(),
1557 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001558}
1559
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001560/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001561static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001562 const TemplateArgument &X,
1563 const TemplateArgument &Y) {
1564 if (X.getKind() != Y.getKind())
1565 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001567 switch (X.getKind()) {
1568 case TemplateArgument::Null:
1569 assert(false && "Comparing NULL template argument");
1570 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001572 case TemplateArgument::Type:
1573 return Context.getCanonicalType(X.getAsType()) ==
1574 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001576 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001577 return X.getAsDecl()->getCanonicalDecl() ==
1578 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Douglas Gregor788cd062009-11-11 01:00:40 +00001580 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001581 case TemplateArgument::TemplateExpansion:
1582 return Context.getCanonicalTemplateName(
1583 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1584 Context.getCanonicalTemplateName(
1585 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001586
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001587 case TemplateArgument::Integral:
1588 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Douglas Gregor788cd062009-11-11 01:00:40 +00001590 case TemplateArgument::Expression: {
1591 llvm::FoldingSetNodeID XID, YID;
1592 X.getAsExpr()->Profile(XID, Context, true);
1593 Y.getAsExpr()->Profile(YID, Context, true);
1594 return XID == YID;
1595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001597 case TemplateArgument::Pack:
1598 if (X.pack_size() != Y.pack_size())
1599 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001600
1601 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1602 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001603 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001604 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001605 if (!isSameTemplateArg(Context, *XP, *YP))
1606 return false;
1607
1608 return true;
1609 }
1610
1611 return false;
1612}
1613
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001614/// \brief Allocate a TemplateArgumentLoc where all locations have
1615/// been initialized to the given location.
1616///
1617/// \param S The semantic analysis object.
1618///
1619/// \param The template argument we are producing template argument
1620/// location information for.
1621///
1622/// \param NTTPType For a declaration template argument, the type of
1623/// the non-type template parameter that corresponds to this template
1624/// argument.
1625///
1626/// \param Loc The source location to use for the resulting template
1627/// argument.
1628static TemplateArgumentLoc
1629getTrivialTemplateArgumentLoc(Sema &S,
1630 const TemplateArgument &Arg,
1631 QualType NTTPType,
1632 SourceLocation Loc) {
1633 switch (Arg.getKind()) {
1634 case TemplateArgument::Null:
1635 llvm_unreachable("Can't get a NULL template argument here");
1636 break;
1637
1638 case TemplateArgument::Type:
1639 return TemplateArgumentLoc(Arg,
1640 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1641
1642 case TemplateArgument::Declaration: {
1643 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001644 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001645 .takeAs<Expr>();
1646 return TemplateArgumentLoc(TemplateArgument(E), E);
1647 }
1648
1649 case TemplateArgument::Integral: {
1650 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001651 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001652 return TemplateArgumentLoc(TemplateArgument(E), E);
1653 }
1654
1655 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001656 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1657
1658 case TemplateArgument::TemplateExpansion:
1659 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1660
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001661 case TemplateArgument::Expression:
1662 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1663
1664 case TemplateArgument::Pack:
1665 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1666 }
1667
1668 return TemplateArgumentLoc();
1669}
1670
1671
1672/// \brief Convert the given deduced template argument and add it to the set of
1673/// fully-converted template arguments.
1674static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1675 DeducedTemplateArgument Arg,
1676 NamedDecl *Template,
1677 QualType NTTPType,
1678 TemplateDeductionInfo &Info,
1679 bool InFunctionTemplate,
1680 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1681 if (Arg.getKind() == TemplateArgument::Pack) {
1682 // This is a template argument pack, so check each of its arguments against
1683 // the template parameter.
1684 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1685 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001686 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001687 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001688 // When converting the deduced template argument, append it to the
1689 // general output list. We need to do this so that the template argument
1690 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001691 DeducedTemplateArgument InnerArg(*PA);
1692 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1693 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1694 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001695 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001696 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001697
1698 // Move the converted template argument into our argument pack.
1699 PackedArgsBuilder.push_back(Output.back());
1700 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001701 }
1702
1703 // Create the resulting argument pack.
1704 TemplateArgument *PackedArgs = 0;
1705 if (!PackedArgsBuilder.empty()) {
1706 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1707 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1708 }
1709 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1710 return false;
1711 }
1712
1713 // Convert the deduced template argument into a template
1714 // argument that we can check, almost as if the user had written
1715 // the template argument explicitly.
1716 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1717 Info.getLocation());
1718
1719 // Check the template argument, converting it as necessary.
1720 return S.CheckTemplateArgument(Param, ArgLoc,
1721 Template,
1722 Template->getLocation(),
1723 Template->getSourceRange().getEnd(),
1724 Output,
1725 InFunctionTemplate
1726 ? (Arg.wasDeducedFromArrayBound()
1727 ? Sema::CTAK_DeducedFromArrayBound
1728 : Sema::CTAK_Deduced)
1729 : Sema::CTAK_Specified);
1730}
1731
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001732/// Complete template argument deduction for a class template partial
1733/// specialization.
1734static Sema::TemplateDeductionResult
1735FinishTemplateArgumentDeduction(Sema &S,
1736 ClassTemplatePartialSpecializationDecl *Partial,
1737 const TemplateArgumentList &TemplateArgs,
1738 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001739 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001740 // Trap errors.
1741 Sema::SFINAETrap Trap(S);
1742
1743 Sema::ContextRAII SavedContext(S, Partial);
1744
1745 // C++ [temp.deduct.type]p2:
1746 // [...] or if any template argument remains neither deduced nor
1747 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001748 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001749 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1750 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001751 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001752 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001753 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001754 return Sema::TDK_Incomplete;
1755 }
1756
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001757 // We have deduced this argument, so it still needs to be
1758 // checked and converted.
1759
1760 // First, for a non-type template parameter type that is
1761 // initialized by a declaration, we need the type of the
1762 // corresponding non-type template parameter.
1763 QualType NTTPType;
1764 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001765 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001766 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001767 if (NTTPType->isDependentType()) {
1768 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1769 Builder.data(), Builder.size());
1770 NTTPType = S.SubstType(NTTPType,
1771 MultiLevelTemplateArgumentList(TemplateArgs),
1772 NTTP->getLocation(),
1773 NTTP->getDeclName());
1774 if (NTTPType.isNull()) {
1775 Info.Param = makeTemplateParameter(Param);
1776 // FIXME: These template arguments are temporary. Free them!
1777 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1778 Builder.data(),
1779 Builder.size()));
1780 return Sema::TDK_SubstitutionFailure;
1781 }
1782 }
1783 }
1784
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001785 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1786 Partial, NTTPType, Info, false,
1787 Builder)) {
1788 Info.Param = makeTemplateParameter(Param);
1789 // FIXME: These template arguments are temporary. Free them!
1790 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1791 Builder.size()));
1792 return Sema::TDK_SubstitutionFailure;
1793 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001794 }
1795
1796 // Form the template argument list from the deduced template arguments.
1797 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001798 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1799 Builder.size());
1800
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001801 Info.reset(DeducedArgumentList);
1802
1803 // Substitute the deduced template arguments into the template
1804 // arguments of the class template partial specialization, and
1805 // verify that the instantiated template arguments are both valid
1806 // and are equivalent to the template arguments originally provided
1807 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001808 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001809 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1810 const TemplateArgumentLoc *PartialTemplateArgs
1811 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001812
1813 // Note that we don't provide the langle and rangle locations.
1814 TemplateArgumentListInfo InstArgs;
1815
Douglas Gregore02e2622010-12-22 21:19:48 +00001816 if (S.Subst(PartialTemplateArgs,
1817 Partial->getNumTemplateArgsAsWritten(),
1818 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1819 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1820 if (ParamIdx >= Partial->getTemplateParameters()->size())
1821 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1822
1823 Decl *Param
1824 = const_cast<NamedDecl *>(
1825 Partial->getTemplateParameters()->getParam(ParamIdx));
1826 Info.Param = makeTemplateParameter(Param);
1827 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1828 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001829 }
1830
Douglas Gregor910f8002010-11-07 23:05:16 +00001831 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001832 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001833 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001834 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001835
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001836 TemplateParameterList *TemplateParams
1837 = ClassTemplate->getTemplateParameters();
1838 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001839 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001840 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001841 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001842 Info.FirstArg = TemplateArgs[I];
1843 Info.SecondArg = InstArg;
1844 return Sema::TDK_NonDeducedMismatch;
1845 }
1846 }
1847
1848 if (Trap.hasErrorOccurred())
1849 return Sema::TDK_SubstitutionFailure;
1850
1851 return Sema::TDK_Success;
1852}
1853
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001854/// \brief Perform template argument deduction to determine whether
1855/// the given template arguments match the given class template
1856/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001857Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001858Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001859 const TemplateArgumentList &TemplateArgs,
1860 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001861 // C++ [temp.class.spec.match]p2:
1862 // A partial specialization matches a given actual template
1863 // argument list if the template arguments of the partial
1864 // specialization can be deduced from the actual template argument
1865 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001866 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001867 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001868 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001869 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001870 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001871 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001873 TemplateArgs, Info, Deduced))
1874 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001875
Douglas Gregor637a4092009-06-10 23:47:09 +00001876 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001877 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001878 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001879 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001880
Douglas Gregorbb260412009-06-14 08:02:22 +00001881 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001882 return Sema::TDK_SubstitutionFailure;
1883
1884 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1885 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001886}
Douglas Gregor031a5882009-06-13 00:26:55 +00001887
Douglas Gregor41128772009-06-26 23:27:24 +00001888/// \brief Determine whether the given type T is a simple-template-id type.
1889static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001890 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001891 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001892 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Douglas Gregor41128772009-06-26 23:27:24 +00001894 return false;
1895}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001896
1897/// \brief Substitute the explicitly-provided template arguments into the
1898/// given function template according to C++ [temp.arg.explicit].
1899///
1900/// \param FunctionTemplate the function template into which the explicit
1901/// template arguments will be substituted.
1902///
Mike Stump1eb44332009-09-09 15:08:12 +00001903/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001904/// arguments.
1905///
Mike Stump1eb44332009-09-09 15:08:12 +00001906/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001907/// with the converted and checked explicit template arguments.
1908///
Mike Stump1eb44332009-09-09 15:08:12 +00001909/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001910/// parameters.
1911///
1912/// \param FunctionType if non-NULL, the result type of the function template
1913/// will also be instantiated and the pointed-to value will be updated with
1914/// the instantiated function type.
1915///
1916/// \param Info if substitution fails for any reason, this object will be
1917/// populated with more information about the failure.
1918///
1919/// \returns TDK_Success if substitution was successful, or some failure
1920/// condition.
1921Sema::TemplateDeductionResult
1922Sema::SubstituteExplicitTemplateArguments(
1923 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001924 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001925 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001926 llvm::SmallVectorImpl<QualType> &ParamTypes,
1927 QualType *FunctionType,
1928 TemplateDeductionInfo &Info) {
1929 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1930 TemplateParameterList *TemplateParams
1931 = FunctionTemplate->getTemplateParameters();
1932
John McCalld5532b62009-11-23 01:53:49 +00001933 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001934 // No arguments to substitute; just copy over the parameter types and
1935 // fill in the function type.
1936 for (FunctionDecl::param_iterator P = Function->param_begin(),
1937 PEnd = Function->param_end();
1938 P != PEnd;
1939 ++P)
1940 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregor83314aa2009-07-08 20:55:45 +00001942 if (FunctionType)
1943 *FunctionType = Function->getType();
1944 return TDK_Success;
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Douglas Gregor83314aa2009-07-08 20:55:45 +00001947 // Substitution of the explicit template arguments into a function template
1948 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001949 SFINAETrap Trap(*this);
1950
Douglas Gregor83314aa2009-07-08 20:55:45 +00001951 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001952 // Template arguments that are present shall be specified in the
1953 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001954 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001955 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001956 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001957
1958 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001959 // explicitly-specified template arguments against this function template,
1960 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001962 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001963 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1964 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001965 if (Inst)
1966 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregor83314aa2009-07-08 20:55:45 +00001968 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001969 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001970 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001971 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001972 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001973 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001974 if (Index >= TemplateParams->size())
1975 Index = TemplateParams->size() - 1;
1976 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001977 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor83314aa2009-07-08 20:55:45 +00001980 // Form the template argument list from the explicitly-specified
1981 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001982 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001983 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001984 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001985
John McCalldf41f182010-10-12 19:40:14 +00001986 // Template argument deduction and the final substitution should be
1987 // done in the context of the templated declaration. Explicit
1988 // argument substitution, on the other hand, needs to happen in the
1989 // calling context.
1990 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1991
Douglas Gregord3731192011-01-10 07:32:04 +00001992 // If we deduced template arguments for a template parameter pack,
1993 // note that the template argument pack is partially substituted and record
1994 // the explicit template arguments. They'll be used as part of deduction
1995 // for this template parameter pack.
1996 bool HasPartiallySubstitutedPack = false;
1997 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1998 const TemplateArgument &Arg = Builder[I];
1999 if (Arg.getKind() == TemplateArgument::Pack) {
2000 HasPartiallySubstitutedPack = true;
2001 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2002 TemplateParams->getParam(I),
2003 Arg.pack_begin(),
2004 Arg.pack_size());
2005 break;
2006 }
2007 }
2008
Douglas Gregor83314aa2009-07-08 20:55:45 +00002009 // Instantiate the types of each of the function parameters given the
2010 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00002011 if (SubstParmTypes(Function->getLocation(),
2012 Function->param_begin(), Function->getNumParams(),
2013 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2014 ParamTypes))
2015 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002016
2017 // If the caller wants a full function type back, instantiate the return
2018 // type and form that function type.
2019 if (FunctionType) {
2020 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00002021 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002022 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002023 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00002024
2025 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00002026 = SubstType(Proto->getResultType(),
2027 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2028 Function->getTypeSpecStartLoc(),
2029 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002030 if (ResultType.isNull() || Trap.hasErrorOccurred())
2031 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
2033 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002034 ParamTypes.data(), ParamTypes.size(),
2035 Proto->isVariadic(),
2036 Proto->getTypeQuals(),
2037 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002038 Function->getDeclName(),
2039 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002040 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2041 return TDK_SubstitutionFailure;
2042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Douglas Gregor83314aa2009-07-08 20:55:45 +00002044 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002045 // Trailing template arguments that can be deduced (14.8.2) may be
2046 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002047 // template arguments can be deduced, they may all be omitted; in this
2048 // case, the empty template argument list <> itself may also be omitted.
2049 //
Douglas Gregord3731192011-01-10 07:32:04 +00002050 // Take all of the explicitly-specified arguments and put them into
2051 // the set of deduced template arguments. Explicitly-specified
2052 // parameter packs, however, will be set to NULL since the deduction
2053 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002054 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002055 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2056 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2057 if (Arg.getKind() == TemplateArgument::Pack)
2058 Deduced.push_back(DeducedTemplateArgument());
2059 else
2060 Deduced.push_back(Arg);
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Douglas Gregor83314aa2009-07-08 20:55:45 +00002063 return TDK_Success;
2064}
2065
Mike Stump1eb44332009-09-09 15:08:12 +00002066/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002067/// checking the deduced template arguments for completeness and forming
2068/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002069Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002070Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00002071 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2072 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002073 FunctionDecl *&Specialization,
2074 TemplateDeductionInfo &Info) {
2075 TemplateParameterList *TemplateParams
2076 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Douglas Gregor83314aa2009-07-08 20:55:45 +00002078 // Template argument deduction for function templates in a SFINAE context.
2079 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002080 SFINAETrap Trap(*this);
2081
Douglas Gregor83314aa2009-07-08 20:55:45 +00002082 // Enter a new template instantiation context while we instantiate the
2083 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002084 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002085 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002086 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2087 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002088 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002089 return TDK_InstantiationDepth;
2090
John McCall96db3102010-04-29 01:18:58 +00002091 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002092
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002093 // C++ [temp.deduct.type]p2:
2094 // [...] or if any template argument remains neither deduced nor
2095 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002096 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002097 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2098 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002099
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002100 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002101 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002102 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002103 // argument, because it was explicitly-specified. Just record the
2104 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002105 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002106 continue;
2107 }
2108
2109 // We have deduced this argument, so it still needs to be
2110 // checked and converted.
2111
2112 // First, for a non-type template parameter type that is
2113 // initialized by a declaration, we need the type of the
2114 // corresponding non-type template parameter.
2115 QualType NTTPType;
2116 if (NonTypeTemplateParmDecl *NTTP
2117 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002118 NTTPType = NTTP->getType();
2119 if (NTTPType->isDependentType()) {
2120 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2121 Builder.data(), Builder.size());
2122 NTTPType = SubstType(NTTPType,
2123 MultiLevelTemplateArgumentList(TemplateArgs),
2124 NTTP->getLocation(),
2125 NTTP->getDeclName());
2126 if (NTTPType.isNull()) {
2127 Info.Param = makeTemplateParameter(Param);
2128 // FIXME: These template arguments are temporary. Free them!
2129 Info.reset(TemplateArgumentList::CreateCopy(Context,
2130 Builder.data(),
2131 Builder.size()));
2132 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002133 }
2134 }
2135 }
2136
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002137 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2138 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002139 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002140 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002141 // FIXME: These template arguments are temporary. Free them!
2142 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002143 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002144 return TDK_SubstitutionFailure;
2145 }
2146
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002147 continue;
2148 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002149
2150 // C++0x [temp.arg.explicit]p3:
2151 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2152 // be deduced to an empty sequence of template arguments.
2153 // FIXME: Where did the word "trailing" come from?
2154 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002155 // We may have had explicitly-specified template arguments for this
2156 // template parameter pack. If so, our empty deduction extends the
2157 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2158 const TemplateArgument *ExplicitArgs;
2159 unsigned NumExplicitArgs;
2160 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2161 &NumExplicitArgs)
2162 == Param)
2163 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2164 else
2165 Builder.push_back(TemplateArgument(0, 0));
2166
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002167 continue;
2168 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002169
2170 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002171 TemplateArgumentLoc DefArg
2172 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2173 FunctionTemplate->getLocation(),
2174 FunctionTemplate->getSourceRange().getEnd(),
2175 Param,
2176 Builder);
2177
2178 // If there was no default argument, deduction is incomplete.
2179 if (DefArg.getArgument().isNull()) {
2180 Info.Param = makeTemplateParameter(
2181 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2182 return TDK_Incomplete;
2183 }
2184
2185 // Check whether we can actually use the default argument.
2186 if (CheckTemplateArgument(Param, DefArg,
2187 FunctionTemplate,
2188 FunctionTemplate->getLocation(),
2189 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002190 Builder,
2191 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002192 Info.Param = makeTemplateParameter(
2193 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002194 // FIXME: These template arguments are temporary. Free them!
2195 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2196 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002197 return TDK_SubstitutionFailure;
2198 }
2199
2200 // If we get here, we successfully used the default template argument.
2201 }
2202
2203 // Form the template argument list from the deduced template arguments.
2204 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002205 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002206 Info.reset(DeducedArgumentList);
2207
Mike Stump1eb44332009-09-09 15:08:12 +00002208 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002209 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002210 DeclContext *Owner = FunctionTemplate->getDeclContext();
2211 if (FunctionTemplate->getFriendObjectKind())
2212 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002213 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002214 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002215 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002216 if (!Specialization)
2217 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Douglas Gregorf8825742009-09-15 18:26:13 +00002219 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2220 FunctionTemplate->getCanonicalDecl());
2221
Mike Stump1eb44332009-09-09 15:08:12 +00002222 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002223 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002224 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2225 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002226 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Douglas Gregor83314aa2009-07-08 20:55:45 +00002228 // There may have been an error that did not prevent us from constructing a
2229 // declaration. Mark the declaration invalid and return with a substitution
2230 // failure.
2231 if (Trap.hasErrorOccurred()) {
2232 Specialization->setInvalidDecl(true);
2233 return TDK_SubstitutionFailure;
2234 }
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor9b623632010-10-12 23:32:35 +00002236 // If we suppressed any diagnostics while performing template argument
2237 // deduction, and if we haven't already instantiated this declaration,
2238 // keep track of these diagnostics. They'll be emitted if this specialization
2239 // is actually used.
2240 if (Info.diag_begin() != Info.diag_end()) {
2241 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2242 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2243 if (Pos == SuppressedDiagnostics.end())
2244 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2245 .append(Info.diag_begin(), Info.diag_end());
2246 }
2247
Mike Stump1eb44332009-09-09 15:08:12 +00002248 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002249}
2250
John McCall9c72c602010-08-27 09:08:28 +00002251/// Gets the type of a function for template-argument-deducton
2252/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002253static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002254 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002255 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002257 if (Method->isInstance()) {
2258 // An instance method that's referenced in a form that doesn't
2259 // look like a member pointer is just invalid.
2260 if (!R.HasFormOfMemberPointer) return QualType();
2261
John McCalleff92132010-02-02 02:21:27 +00002262 return Context.getMemberPointerType(Fn->getType(),
2263 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002264 }
2265
2266 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002267 return Context.getPointerType(Fn->getType());
2268}
2269
2270/// Apply the deduction rules for overload sets.
2271///
2272/// \return the null type if this argument should be treated as an
2273/// undeduced context
2274static QualType
2275ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002276 Expr *Arg, QualType ParamType,
2277 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002278
2279 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002280
John McCall9c72c602010-08-27 09:08:28 +00002281 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002282
Douglas Gregor75f21af2010-08-30 21:04:23 +00002283 // C++0x [temp.deduct.call]p4
2284 unsigned TDF = 0;
2285 if (ParamWasReference)
2286 TDF |= TDF_ParamWithReferenceType;
2287 if (R.IsAddressOfOperand)
2288 TDF |= TDF_IgnoreQualifiers;
2289
John McCalleff92132010-02-02 02:21:27 +00002290 // If there were explicit template arguments, we can only find
2291 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2292 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002293 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002294 // But we can still look for an explicit specialization.
2295 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002296 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002297 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002298 return QualType();
2299 }
2300
2301 // C++0x [temp.deduct.call]p6:
2302 // When P is a function type, pointer to function type, or pointer
2303 // to member function type:
2304
2305 if (!ParamType->isFunctionType() &&
2306 !ParamType->isFunctionPointerType() &&
2307 !ParamType->isMemberFunctionPointerType())
2308 return QualType();
2309
2310 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002311 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2312 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002313 NamedDecl *D = (*I)->getUnderlyingDecl();
2314
2315 // - If the argument is an overload set containing one or more
2316 // function templates, the parameter is treated as a
2317 // non-deduced context.
2318 if (isa<FunctionTemplateDecl>(D))
2319 return QualType();
2320
2321 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002322 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2323 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002324
Douglas Gregor75f21af2010-08-30 21:04:23 +00002325 // Function-to-pointer conversion.
2326 if (!ParamWasReference && ParamType->isPointerType() &&
2327 ArgType->isFunctionType())
2328 ArgType = S.Context.getPointerType(ArgType);
2329
John McCalleff92132010-02-02 02:21:27 +00002330 // - If the argument is an overload set (not containing function
2331 // templates), trial argument deduction is attempted using each
2332 // of the members of the set. If deduction succeeds for only one
2333 // of the overload set members, that member is used as the
2334 // argument value for the deduction. If deduction succeeds for
2335 // more than one member of the overload set the parameter is
2336 // treated as a non-deduced context.
2337
2338 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2339 // Type deduction is done independently for each P/A pair, and
2340 // the deduced template argument values are then combined.
2341 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002342 llvm::SmallVector<DeducedTemplateArgument, 8>
2343 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002344 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002345 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002346 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002347 ParamType, ArgType,
2348 Info, Deduced, TDF);
2349 if (Result) continue;
2350 if (!Match.isNull()) return QualType();
2351 Match = ArgType;
2352 }
2353
2354 return Match;
2355}
2356
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002357/// \brief Perform the adjustments to the parameter and argument types
2358/// described in C++ [temp.deduct.call].
2359///
2360/// \returns true if the caller should not attempt to perform any template
2361/// argument deduction based on this P/A pair.
2362static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2363 TemplateParameterList *TemplateParams,
2364 QualType &ParamType,
2365 QualType &ArgType,
2366 Expr *Arg,
2367 unsigned &TDF) {
2368 // C++0x [temp.deduct.call]p3:
2369 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2370 // are ignored for type deduction.
2371 if (ParamType.getCVRQualifiers())
2372 ParamType = ParamType.getLocalUnqualifiedType();
2373 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2374 if (ParamRefType) {
2375 // [...] If P is a reference type, the type referred to by P is used
2376 // for type deduction.
2377 ParamType = ParamRefType->getPointeeType();
2378 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002379
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002380 // Overload sets usually make this parameter an undeduced
2381 // context, but there are sometimes special circumstances.
2382 if (ArgType == S.Context.OverloadTy) {
2383 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2384 Arg, ParamType,
2385 ParamRefType != 0);
2386 if (ArgType.isNull())
2387 return true;
2388 }
2389
2390 if (ParamRefType) {
2391 // C++0x [temp.deduct.call]p3:
2392 // [...] If P is of the form T&&, where T is a template parameter, and
2393 // the argument is an lvalue, the type A& is used in place of A for
2394 // type deduction.
2395 if (ParamRefType->isRValueReferenceType() &&
2396 ParamRefType->getAs<TemplateTypeParmType>() &&
2397 Arg->isLValue())
2398 ArgType = S.Context.getLValueReferenceType(ArgType);
2399 } else {
2400 // C++ [temp.deduct.call]p2:
2401 // If P is not a reference type:
2402 // - If A is an array type, the pointer type produced by the
2403 // array-to-pointer standard conversion (4.2) is used in place of
2404 // A for type deduction; otherwise,
2405 if (ArgType->isArrayType())
2406 ArgType = S.Context.getArrayDecayedType(ArgType);
2407 // - If A is a function type, the pointer type produced by the
2408 // function-to-pointer standard conversion (4.3) is used in place
2409 // of A for type deduction; otherwise,
2410 else if (ArgType->isFunctionType())
2411 ArgType = S.Context.getPointerType(ArgType);
2412 else {
2413 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2414 // type are ignored for type deduction.
2415 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2416 if (ArgType.getCVRQualifiers())
2417 ArgType = ArgType.getUnqualifiedType();
2418 }
2419 }
2420
2421 // C++0x [temp.deduct.call]p4:
2422 // In general, the deduction process attempts to find template argument
2423 // values that will make the deduced A identical to A (after the type A
2424 // is transformed as described above). [...]
2425 TDF = TDF_SkipNonDependent;
2426
2427 // - If the original P is a reference type, the deduced A (i.e., the
2428 // type referred to by the reference) can be more cv-qualified than
2429 // the transformed A.
2430 if (ParamRefType)
2431 TDF |= TDF_ParamWithReferenceType;
2432 // - The transformed A can be another pointer or pointer to member
2433 // type that can be converted to the deduced A via a qualification
2434 // conversion (4.4).
2435 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2436 ArgType->isObjCObjectPointerType())
2437 TDF |= TDF_IgnoreQualifiers;
2438 // - If P is a class and P has the form simple-template-id, then the
2439 // transformed A can be a derived class of the deduced A. Likewise,
2440 // if P is a pointer to a class of the form simple-template-id, the
2441 // transformed A can be a pointer to a derived class pointed to by
2442 // the deduced A.
2443 if (isSimpleTemplateIdType(ParamType) ||
2444 (isa<PointerType>(ParamType) &&
2445 isSimpleTemplateIdType(
2446 ParamType->getAs<PointerType>()->getPointeeType())))
2447 TDF |= TDF_DerivedClass;
2448
2449 return false;
2450}
2451
Douglas Gregore53060f2009-06-25 22:08:12 +00002452/// \brief Perform template argument deduction from a function call
2453/// (C++ [temp.deduct.call]).
2454///
2455/// \param FunctionTemplate the function template for which we are performing
2456/// template argument deduction.
2457///
Douglas Gregor48026d22010-01-11 18:40:55 +00002458/// \param ExplicitTemplateArguments the explicit template arguments provided
2459/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002460///
Douglas Gregore53060f2009-06-25 22:08:12 +00002461/// \param Args the function call arguments
2462///
2463/// \param NumArgs the number of arguments in Args
2464///
Douglas Gregor48026d22010-01-11 18:40:55 +00002465/// \param Name the name of the function being called. This is only significant
2466/// when the function template is a conversion function template, in which
2467/// case this routine will also perform template argument deduction based on
2468/// the function to which
2469///
Douglas Gregore53060f2009-06-25 22:08:12 +00002470/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002471/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002472/// template argument deduction.
2473///
2474/// \param Info the argument will be updated to provide additional information
2475/// about template argument deduction.
2476///
2477/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002478Sema::TemplateDeductionResult
2479Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002480 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002481 Expr **Args, unsigned NumArgs,
2482 FunctionDecl *&Specialization,
2483 TemplateDeductionInfo &Info) {
2484 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002485
Douglas Gregore53060f2009-06-25 22:08:12 +00002486 // C++ [temp.deduct.call]p1:
2487 // Template argument deduction is done by comparing each function template
2488 // parameter type (call it P) with the type of the corresponding argument
2489 // of the call (call it A) as described below.
2490 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002491 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002492 return TDK_TooFewArguments;
2493 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002494 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002495 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002496 if (Proto->isTemplateVariadic())
2497 /* Do nothing */;
2498 else if (Proto->isVariadic())
2499 CheckArgs = Function->getNumParams();
2500 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002501 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002502 }
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002504 // The types of the parameters from which we will perform template argument
2505 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002506 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002507 TemplateParameterList *TemplateParams
2508 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002509 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002510 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002511 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002512 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002513 TemplateDeductionResult Result =
2514 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002515 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002516 Deduced,
2517 ParamTypes,
2518 0,
2519 Info);
2520 if (Result)
2521 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002522
2523 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002524 } else {
2525 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002526 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002527 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2528 }
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002530 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002531 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002532 unsigned ArgIdx = 0;
2533 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2534 ParamIdx != NumParams; ++ParamIdx) {
2535 QualType ParamType = ParamTypes[ParamIdx];
2536
2537 const PackExpansionType *ParamExpansion
2538 = dyn_cast<PackExpansionType>(ParamType);
2539 if (!ParamExpansion) {
2540 // Simple case: matching a function parameter to a function argument.
2541 if (ArgIdx >= CheckArgs)
2542 break;
2543
2544 Expr *Arg = Args[ArgIdx++];
2545 QualType ArgType = Arg->getType();
2546 unsigned TDF = 0;
2547 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2548 ParamType, ArgType, Arg,
2549 TDF))
2550 continue;
2551
2552 if (TemplateDeductionResult Result
2553 = ::DeduceTemplateArguments(*this, TemplateParams,
2554 ParamType, ArgType, Info, Deduced,
2555 TDF))
2556 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002558 // FIXME: we need to check that the deduced A is the same as A,
2559 // modulo the various allowed differences.
2560 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002561 }
2562
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002563 // C++0x [temp.deduct.call]p1:
2564 // For a function parameter pack that occurs at the end of the
2565 // parameter-declaration-list, the type A of each remaining argument of
2566 // the call is compared with the type P of the declarator-id of the
2567 // function parameter pack. Each comparison deduces template arguments
2568 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002569 // the function parameter pack. For a function parameter pack that does
2570 // not occur at the end of the parameter-declaration-list, the type of
2571 // the parameter pack is a non-deduced context.
2572 if (ParamIdx + 1 < NumParams)
2573 break;
2574
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002575 QualType ParamPattern = ParamExpansion->getPattern();
2576 llvm::SmallVector<unsigned, 2> PackIndices;
2577 {
2578 llvm::BitVector SawIndices(TemplateParams->size());
2579 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2580 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2581 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2582 unsigned Depth, Index;
2583 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2584 if (Depth == 0 && !SawIndices[Index]) {
2585 SawIndices[Index] = true;
2586 PackIndices.push_back(Index);
2587 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002588 }
2589 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002590 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2591
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002592 // Keep track of the deduced template arguments for each parameter pack
2593 // expanded by this pack expansion (the outer index) and for each
2594 // template argument (the inner SmallVectors).
2595 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002596 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002597 llvm::SmallVector<DeducedTemplateArgument, 2>
2598 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002599 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2600 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002601 bool HasAnyArguments = false;
2602 for (; ArgIdx < NumArgs; ++ArgIdx) {
2603 HasAnyArguments = true;
2604
2605 ParamType = ParamPattern;
2606 Expr *Arg = Args[ArgIdx];
2607 QualType ArgType = Arg->getType();
2608 unsigned TDF = 0;
2609 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2610 ParamType, ArgType, Arg,
2611 TDF)) {
2612 // We can't actually perform any deduction for this argument, so stop
2613 // deduction at this point.
2614 ++ArgIdx;
2615 break;
2616 }
2617
2618 if (TemplateDeductionResult Result
2619 = ::DeduceTemplateArguments(*this, TemplateParams,
2620 ParamType, ArgType, Info, Deduced,
2621 TDF))
2622 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002623
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002624 // Capture the deduced template arguments for each parameter pack expanded
2625 // by this pack expansion, add them to the list of arguments we've deduced
2626 // for that pack, then clear out the deduced argument.
2627 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2628 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2629 if (!DeducedArg.isNull()) {
2630 NewlyDeducedPacks[I].push_back(DeducedArg);
2631 DeducedArg = DeducedTemplateArgument();
2632 }
2633 }
2634 }
2635
2636 // Build argument packs for each of the parameter packs expanded by this
2637 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002638 if (Sema::TemplateDeductionResult Result
2639 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2640 Deduced, PackIndices, SavedPacks,
2641 NewlyDeducedPacks, Info))
2642 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002644 // After we've matching against a parameter pack, we're done.
2645 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002646 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002647
Mike Stump1eb44332009-09-09 15:08:12 +00002648 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002649 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002650 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002651}
2652
Douglas Gregor83314aa2009-07-08 20:55:45 +00002653/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002654/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2655/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002656///
2657/// \param FunctionTemplate the function template for which we are performing
2658/// template argument deduction.
2659///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002660/// \param ExplicitTemplateArguments the explicitly-specified template
2661/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002662///
2663/// \param ArgFunctionType the function type that will be used as the
2664/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002665/// function template's function type. This type may be NULL, if there is no
2666/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002667///
2668/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002669/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002670/// template argument deduction.
2671///
2672/// \param Info the argument will be updated to provide additional information
2673/// about template argument deduction.
2674///
2675/// \returns the result of template argument deduction.
2676Sema::TemplateDeductionResult
2677Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002678 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002679 QualType ArgFunctionType,
2680 FunctionDecl *&Specialization,
2681 TemplateDeductionInfo &Info) {
2682 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2683 TemplateParameterList *TemplateParams
2684 = FunctionTemplate->getTemplateParameters();
2685 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Douglas Gregor83314aa2009-07-08 20:55:45 +00002687 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002688 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002689 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2690 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002691 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002692 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002693 if (TemplateDeductionResult Result
2694 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002695 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002696 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002697 &FunctionType, Info))
2698 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002699
2700 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002701 }
2702
2703 // Template argument deduction for function templates in a SFINAE context.
2704 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002705 SFINAETrap Trap(*this);
2706
John McCalleff92132010-02-02 02:21:27 +00002707 Deduced.resize(TemplateParams->size());
2708
Douglas Gregor4b52e252009-12-21 23:17:24 +00002709 if (!ArgFunctionType.isNull()) {
2710 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002711 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002712 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002713 FunctionType, ArgFunctionType, Info,
2714 Deduced, 0))
2715 return Result;
2716 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002717
2718 if (TemplateDeductionResult Result
2719 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2720 NumExplicitlySpecified,
2721 Specialization, Info))
2722 return Result;
2723
2724 // If the requested function type does not match the actual type of the
2725 // specialization, template argument deduction fails.
2726 if (!ArgFunctionType.isNull() &&
2727 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2728 return TDK_NonDeducedMismatch;
2729
2730 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002731}
2732
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002733/// \brief Deduce template arguments for a templated conversion
2734/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2735/// conversion function template specialization.
2736Sema::TemplateDeductionResult
2737Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2738 QualType ToType,
2739 CXXConversionDecl *&Specialization,
2740 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002741 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002742 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2743 QualType FromType = Conv->getConversionType();
2744
2745 // Canonicalize the types for deduction.
2746 QualType P = Context.getCanonicalType(FromType);
2747 QualType A = Context.getCanonicalType(ToType);
2748
2749 // C++0x [temp.deduct.conv]p3:
2750 // If P is a reference type, the type referred to by P is used for
2751 // type deduction.
2752 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2753 P = PRef->getPointeeType();
2754
2755 // C++0x [temp.deduct.conv]p3:
2756 // If A is a reference type, the type referred to by A is used
2757 // for type deduction.
2758 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2759 A = ARef->getPointeeType();
2760 // C++ [temp.deduct.conv]p2:
2761 //
Mike Stump1eb44332009-09-09 15:08:12 +00002762 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002763 else {
2764 assert(!A->isReferenceType() && "Reference types were handled above");
2765
2766 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002767 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002768 // of P for type deduction; otherwise,
2769 if (P->isArrayType())
2770 P = Context.getArrayDecayedType(P);
2771 // - If P is a function type, the pointer type produced by the
2772 // function-to-pointer standard conversion (4.3) is used in
2773 // place of P for type deduction; otherwise,
2774 else if (P->isFunctionType())
2775 P = Context.getPointerType(P);
2776 // - If P is a cv-qualified type, the top level cv-qualifiers of
2777 // P’s type are ignored for type deduction.
2778 else
2779 P = P.getUnqualifiedType();
2780
2781 // C++0x [temp.deduct.conv]p3:
2782 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2783 // type are ignored for type deduction.
2784 A = A.getUnqualifiedType();
2785 }
2786
2787 // Template argument deduction for function templates in a SFINAE context.
2788 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002789 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002790
2791 // C++ [temp.deduct.conv]p1:
2792 // Template argument deduction is done by comparing the return
2793 // type of the template conversion function (call it P) with the
2794 // type that is required as the result of the conversion (call it
2795 // A) as described in 14.8.2.4.
2796 TemplateParameterList *TemplateParams
2797 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002798 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002799 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002800
2801 // C++0x [temp.deduct.conv]p4:
2802 // In general, the deduction process attempts to find template
2803 // argument values that will make the deduced A identical to
2804 // A. However, there are two cases that allow a difference:
2805 unsigned TDF = 0;
2806 // - If the original A is a reference type, A can be more
2807 // cv-qualified than the deduced A (i.e., the type referred to
2808 // by the reference)
2809 if (ToType->isReferenceType())
2810 TDF |= TDF_ParamWithReferenceType;
2811 // - The deduced A can be another pointer or pointer to member
2812 // type that can be converted to A via a qualification
2813 // conversion.
2814 //
2815 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2816 // both P and A are pointers or member pointers. In this case, we
2817 // just ignore cv-qualifiers completely).
2818 if ((P->isPointerType() && A->isPointerType()) ||
2819 (P->isMemberPointerType() && P->isMemberPointerType()))
2820 TDF |= TDF_IgnoreQualifiers;
2821 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002822 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002823 P, A, Info, Deduced, TDF))
2824 return Result;
2825
2826 // FIXME: we need to check that the deduced A is the same as A,
2827 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002829 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002830 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002831 FunctionDecl *Spec = 0;
2832 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002833 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2834 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002835 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2836 return Result;
2837}
2838
Douglas Gregor4b52e252009-12-21 23:17:24 +00002839/// \brief Deduce template arguments for a function template when there is
2840/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2841///
2842/// \param FunctionTemplate the function template for which we are performing
2843/// template argument deduction.
2844///
2845/// \param ExplicitTemplateArguments the explicitly-specified template
2846/// arguments.
2847///
2848/// \param Specialization if template argument deduction was successful,
2849/// this will be set to the function template specialization produced by
2850/// template argument deduction.
2851///
2852/// \param Info the argument will be updated to provide additional information
2853/// about template argument deduction.
2854///
2855/// \returns the result of template argument deduction.
2856Sema::TemplateDeductionResult
2857Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2858 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2859 FunctionDecl *&Specialization,
2860 TemplateDeductionInfo &Info) {
2861 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2862 QualType(), Specialization, Info);
2863}
2864
Douglas Gregor8a514912009-09-14 18:39:43 +00002865static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002866MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2867 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002868 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002869 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002870
2871/// \brief If this is a non-static member function,
2872static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2873 CXXMethodDecl *Method,
2874 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2875 if (Method->isStatic())
2876 return;
2877
2878 // C++ [over.match.funcs]p4:
2879 //
2880 // For non-static member functions, the type of the implicit
2881 // object parameter is
2882 // — "lvalue reference to cv X" for functions declared without a
2883 // ref-qualifier or with the & ref-qualifier
2884 // - "rvalue reference to cv X" for functions declared with the
2885 // && ref-qualifier
2886 //
2887 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2888 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2889 ArgTy = Context.getQualifiedType(ArgTy,
2890 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2891 ArgTy = Context.getLValueReferenceType(ArgTy);
2892 ArgTypes.push_back(ArgTy);
2893}
2894
Douglas Gregor8a514912009-09-14 18:39:43 +00002895/// \brief Determine whether the function template \p FT1 is at least as
2896/// specialized as \p FT2.
2897static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002898 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002899 FunctionTemplateDecl *FT1,
2900 FunctionTemplateDecl *FT2,
2901 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002902 unsigned NumCallArguments,
Douglas Gregor8a514912009-09-14 18:39:43 +00002903 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2904 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2905 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2906 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2907 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2908
2909 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2910 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002911 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002912 Deduced.resize(TemplateParams->size());
2913
2914 // C++0x [temp.deduct.partial]p3:
2915 // The types used to determine the ordering depend on the context in which
2916 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002917 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002918 CXXMethodDecl *Method1 = 0;
2919 CXXMethodDecl *Method2 = 0;
2920 bool IsNonStatic2 = false;
2921 bool IsNonStatic1 = false;
2922 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002923 switch (TPOC) {
2924 case TPOC_Call: {
2925 // - In the context of a function call, the function parameter types are
2926 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002927 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2928 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2929 IsNonStatic1 = Method1 && !Method1->isStatic();
2930 IsNonStatic2 = Method2 && !Method2->isStatic();
2931
2932 // C++0x [temp.func.order]p3:
2933 // [...] If only one of the function templates is a non-static
2934 // member, that function template is considered to have a new
2935 // first parameter inserted in its function parameter list. The
2936 // new parameter is of type "reference to cv A," where cv are
2937 // the cv-qualifiers of the function template (if any) and A is
2938 // the class of which the function template is a member.
2939 //
2940 // C++98/03 doesn't have this provision, so instead we drop the
2941 // first argument of the free function or static member, which
2942 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002943 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002944 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2945 IsNonStatic2 && !IsNonStatic1;
2946 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002947 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002948 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002949 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002950
2951 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002952 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2953 IsNonStatic1 && !IsNonStatic2;
2954 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002955 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2956 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002957 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002958
2959 // C++ [temp.func.order]p5:
2960 // The presence of unused ellipsis and default arguments has no effect on
2961 // the partial ordering of function templates.
2962 if (Args1.size() > NumCallArguments)
2963 Args1.resize(NumCallArguments);
2964 if (Args2.size() > NumCallArguments)
2965 Args2.resize(NumCallArguments);
2966 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
2967 Args1.data(), Args1.size(), Info, Deduced,
2968 TDF_None, /*PartialOrdering=*/true,
2969 QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00002970 return false;
2971
2972 break;
2973 }
2974
2975 case TPOC_Conversion:
2976 // - In the context of a call to a conversion operator, the return types
2977 // of the conversion function templates are used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002978 if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
2979 Proto1->getResultType(), Info, Deduced,
2980 TDF_None, /*PartialOrdering=*/true,
2981 QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00002982 return false;
2983 break;
2984
2985 case TPOC_Other:
2986 // - In other contexts (14.6.6.2) the function template’s function type
2987 // is used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002988 // FIXME: Don't we actually want to perform the adjustments on the parameter
2989 // types?
2990 if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
2991 FD1->getType(), Info, Deduced, TDF_None,
2992 /*PartialOrdering=*/true, QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00002993 return false;
2994 break;
2995 }
2996
2997 // C++0x [temp.deduct.partial]p11:
2998 // In most cases, all template parameters must have values in order for
2999 // deduction to succeed, but for partial ordering purposes a template
3000 // parameter may remain without a value provided it is not used in the
3001 // types being used for partial ordering. [ Note: a template parameter used
3002 // in a non-deduced context is considered used. -end note]
3003 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3004 for (; ArgIdx != NumArgs; ++ArgIdx)
3005 if (Deduced[ArgIdx].isNull())
3006 break;
3007
3008 if (ArgIdx == NumArgs) {
3009 // All template arguments were deduced. FT1 is at least as specialized
3010 // as FT2.
3011 return true;
3012 }
3013
Douglas Gregore73bb602009-09-14 21:25:05 +00003014 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003015 llvm::SmallVector<bool, 4> UsedParameters;
3016 UsedParameters.resize(TemplateParams->size());
3017 switch (TPOC) {
3018 case TPOC_Call: {
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003019 unsigned NumParams = std::min(NumCallArguments,
3020 std::min(Proto1->getNumArgs(),
3021 Proto2->getNumArgs()));
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003022 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3023 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3024 TemplateParams->getDepth(), UsedParameters);
3025 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003026 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3027 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003028 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003029 break;
3030 }
3031
3032 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003033 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3034 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003035 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003036 break;
3037
3038 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003039 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3040 TemplateParams->getDepth(),
3041 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003042 break;
3043 }
3044
3045 for (; ArgIdx != NumArgs; ++ArgIdx)
3046 // If this argument had no value deduced but was used in one of the types
3047 // used for partial ordering, then deduction fails.
3048 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3049 return false;
3050
3051 return true;
3052}
3053
3054
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003055/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003056/// to the rules of function template partial ordering (C++ [temp.func.order]).
3057///
3058/// \param FT1 the first function template
3059///
3060/// \param FT2 the second function template
3061///
Douglas Gregor8a514912009-09-14 18:39:43 +00003062/// \param TPOC the context in which we are performing partial ordering of
3063/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003064///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003065/// \param NumCallArguments The number of arguments in a call, used only
3066/// when \c TPOC is \c TPOC_Call.
3067///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003068/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003069/// template is more specialized, returns NULL.
3070FunctionTemplateDecl *
3071Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3072 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003073 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003074 TemplatePartialOrderingContext TPOC,
3075 unsigned NumCallArguments) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003076 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003077 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3078 NumCallArguments, 0);
John McCall5769d612010-02-08 23:07:23 +00003079 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003080 NumCallArguments,
Douglas Gregor8a514912009-09-14 18:39:43 +00003081 &QualifierComparisons);
3082
3083 if (Better1 != Better2) // We have a clear winner
3084 return Better1? FT1 : FT2;
3085
3086 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003087 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003088
3089
3090 // C++0x [temp.deduct.partial]p10:
3091 // If for each type being considered a given template is at least as
3092 // specialized for all types and more specialized for some set of types and
3093 // the other template is not more specialized for any types or is not at
3094 // least as specialized for any types, then the given template is more
3095 // specialized than the other template. Otherwise, neither template is more
3096 // specialized than the other.
3097 Better1 = false;
3098 Better2 = false;
3099 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3100 // C++0x [temp.deduct.partial]p9:
3101 // If, for a given type, deduction succeeds in both directions (i.e., the
3102 // types are identical after the transformations above) and if the type
3103 // from the argument template is more cv-qualified than the type from the
3104 // parameter template (as described above) that type is considered to be
3105 // more specialized than the other. If neither type is more cv-qualified
3106 // than the other then neither type is more specialized than the other.
3107 switch (QualifierComparisons[I]) {
3108 case NeitherMoreQualified:
3109 break;
3110
3111 case ParamMoreQualified:
3112 Better1 = true;
3113 if (Better2)
3114 return 0;
3115 break;
3116
3117 case ArgMoreQualified:
3118 Better2 = true;
3119 if (Better1)
3120 return 0;
3121 break;
3122 }
3123 }
3124
3125 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003126 if (Better1)
3127 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003128 else if (Better2)
3129 return FT2;
3130 else
3131 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003132}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003133
Douglas Gregord5a423b2009-09-25 18:43:00 +00003134/// \brief Determine if the two templates are equivalent.
3135static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3136 if (T1 == T2)
3137 return true;
3138
3139 if (!T1 || !T2)
3140 return false;
3141
3142 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3143}
3144
3145/// \brief Retrieve the most specialized of the given function template
3146/// specializations.
3147///
John McCallc373d482010-01-27 01:50:18 +00003148/// \param SpecBegin the start iterator of the function template
3149/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003150///
John McCallc373d482010-01-27 01:50:18 +00003151/// \param SpecEnd the end iterator of the function template
3152/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003153///
3154/// \param TPOC the partial ordering context to use to compare the function
3155/// template specializations.
3156///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003157/// \param NumCallArguments The number of arguments in a call, used only
3158/// when \c TPOC is \c TPOC_Call.
3159///
Douglas Gregord5a423b2009-09-25 18:43:00 +00003160/// \param Loc the location where the ambiguity or no-specializations
3161/// diagnostic should occur.
3162///
3163/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3164/// no matching candidates.
3165///
3166/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3167/// occurs.
3168///
3169/// \param CandidateDiag partial diagnostic used for each function template
3170/// specialization that is a candidate in the ambiguous ordering. One parameter
3171/// in this diagnostic should be unbound, which will correspond to the string
3172/// describing the template arguments for the function template specialization.
3173///
3174/// \param Index if non-NULL and the result of this function is non-nULL,
3175/// receives the index corresponding to the resulting function template
3176/// specialization.
3177///
3178/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003179/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003180///
3181/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3182/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003183UnresolvedSetIterator
3184Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003185 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00003186 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003187 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00003188 SourceLocation Loc,
3189 const PartialDiagnostic &NoneDiag,
3190 const PartialDiagnostic &AmbigDiag,
3191 const PartialDiagnostic &CandidateDiag) {
3192 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003193 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003194 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003195 }
3196
John McCallc373d482010-01-27 01:50:18 +00003197 if (SpecBegin + 1 == SpecEnd)
3198 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003199
3200 // Find the function template that is better than all of the templates it
3201 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003202 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003203 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003204 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003205 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003206 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3207 FunctionTemplateDecl *Challenger
3208 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003209 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003210 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003211 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003212 Challenger)) {
3213 Best = I;
3214 BestTemplate = Challenger;
3215 }
3216 }
3217
3218 // Make sure that the "best" function template is more specialized than all
3219 // of the others.
3220 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003221 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3222 FunctionTemplateDecl *Challenger
3223 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003224 if (I != Best &&
3225 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003226 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003227 BestTemplate)) {
3228 Ambiguous = true;
3229 break;
3230 }
3231 }
3232
3233 if (!Ambiguous) {
3234 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003235 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003236 }
3237
3238 // Diagnose the ambiguity.
3239 Diag(Loc, AmbigDiag);
3240
3241 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003242 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3243 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003244 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003245 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3246 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003247
John McCallc373d482010-01-27 01:50:18 +00003248 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003249}
3250
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003251/// \brief Returns the more specialized class template partial specialization
3252/// according to the rules of partial ordering of class template partial
3253/// specializations (C++ [temp.class.order]).
3254///
3255/// \param PS1 the first class template partial specialization
3256///
3257/// \param PS2 the second class template partial specialization
3258///
3259/// \returns the more specialized class template partial specialization. If
3260/// neither partial specialization is more specialized, returns NULL.
3261ClassTemplatePartialSpecializationDecl *
3262Sema::getMoreSpecializedPartialSpecialization(
3263 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003264 ClassTemplatePartialSpecializationDecl *PS2,
3265 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003266 // C++ [temp.class.order]p1:
3267 // For two class template partial specializations, the first is at least as
3268 // specialized as the second if, given the following rewrite to two
3269 // function templates, the first function template is at least as
3270 // specialized as the second according to the ordering rules for function
3271 // templates (14.6.6.2):
3272 // - the first function template has the same template parameters as the
3273 // first partial specialization and has a single function parameter
3274 // whose type is a class template specialization with the template
3275 // arguments of the first partial specialization, and
3276 // - the second function template has the same template parameters as the
3277 // second partial specialization and has a single function parameter
3278 // whose type is a class template specialization with the template
3279 // arguments of the second partial specialization.
3280 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003281 // Rather than synthesize function templates, we merely perform the
3282 // equivalent partial ordering by performing deduction directly on
3283 // the template arguments of the class template partial
3284 // specializations. This computation is slightly simpler than the
3285 // general problem of function template partial ordering, because
3286 // class template partial specializations are more constrained. We
3287 // know that every template parameter is deducible from the class
3288 // template partial specialization's template arguments, for
3289 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003290 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003291 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003292
3293 QualType PT1 = PS1->getInjectedSpecializationType();
3294 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003295
3296 // Determine whether PS1 is at least as specialized as PS2
3297 Deduced.resize(PS2->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003298 bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3299 PT2, PT1, Info, Deduced, TDF_None,
3300 /*PartialOrdering=*/true,
3301 /*QualifierComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003302 if (Better1) {
3303 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3304 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003305 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3306 PS1->getTemplateArgs(),
3307 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003308 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003309
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003310 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003311 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003312 Deduced.resize(PS1->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003313 bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3314 PT1, PT2, Info, Deduced, TDF_None,
3315 /*PartialOrdering=*/true,
3316 /*QualifierComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003317 if (Better2) {
3318 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3319 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003320 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3321 PS2->getTemplateArgs(),
3322 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003323 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003324
3325 if (Better1 == Better2)
3326 return 0;
3327
3328 return Better1? PS1 : PS2;
3329}
3330
Mike Stump1eb44332009-09-09 15:08:12 +00003331static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003332MarkUsedTemplateParameters(Sema &SemaRef,
3333 const TemplateArgument &TemplateArg,
3334 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003335 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003336 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003337
Douglas Gregore73bb602009-09-14 21:25:05 +00003338/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003339/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003340static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003341MarkUsedTemplateParameters(Sema &SemaRef,
3342 const Expr *E,
3343 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003344 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003345 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003346 // We can deduce from a pack expansion.
3347 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3348 E = Expansion->getPattern();
3349
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003350 // Skip through any implicit casts we added while type-checking.
3351 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3352 E = ICE->getSubExpr();
3353
Douglas Gregore73bb602009-09-14 21:25:05 +00003354 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3355 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003356 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003357 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003358 return;
3359
Mike Stump1eb44332009-09-09 15:08:12 +00003360 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003361 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3362 if (!NTTP)
3363 return;
3364
Douglas Gregored9c0f92009-10-29 00:04:11 +00003365 if (NTTP->getDepth() == Depth)
3366 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003367}
3368
Douglas Gregore73bb602009-09-14 21:25:05 +00003369/// \brief Mark the template parameters that are used by the given
3370/// nested name specifier.
3371static void
3372MarkUsedTemplateParameters(Sema &SemaRef,
3373 NestedNameSpecifier *NNS,
3374 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003375 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003376 llvm::SmallVectorImpl<bool> &Used) {
3377 if (!NNS)
3378 return;
3379
Douglas Gregored9c0f92009-10-29 00:04:11 +00003380 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3381 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003382 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003383 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003384}
3385
3386/// \brief Mark the template parameters that are used by the given
3387/// template name.
3388static void
3389MarkUsedTemplateParameters(Sema &SemaRef,
3390 TemplateName Name,
3391 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003392 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003393 llvm::SmallVectorImpl<bool> &Used) {
3394 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3395 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003396 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3397 if (TTP->getDepth() == Depth)
3398 Used[TTP->getIndex()] = true;
3399 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003400 return;
3401 }
3402
Douglas Gregor788cd062009-11-11 01:00:40 +00003403 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3404 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3405 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003406 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003407 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3408 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003409}
3410
3411/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003412/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003413static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003414MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3415 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003416 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003417 llvm::SmallVectorImpl<bool> &Used) {
3418 if (T.isNull())
3419 return;
3420
Douglas Gregor031a5882009-06-13 00:26:55 +00003421 // Non-dependent types have nothing deducible
3422 if (!T->isDependentType())
3423 return;
3424
3425 T = SemaRef.Context.getCanonicalType(T);
3426 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003427 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003428 MarkUsedTemplateParameters(SemaRef,
3429 cast<PointerType>(T)->getPointeeType(),
3430 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003431 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003432 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003433 break;
3434
3435 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003436 MarkUsedTemplateParameters(SemaRef,
3437 cast<BlockPointerType>(T)->getPointeeType(),
3438 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003439 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003440 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003441 break;
3442
3443 case Type::LValueReference:
3444 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003445 MarkUsedTemplateParameters(SemaRef,
3446 cast<ReferenceType>(T)->getPointeeType(),
3447 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003448 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003449 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003450 break;
3451
3452 case Type::MemberPointer: {
3453 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003454 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003455 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003456 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003457 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003458 break;
3459 }
3460
3461 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003462 MarkUsedTemplateParameters(SemaRef,
3463 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003464 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003465 // Fall through to check the element type
3466
3467 case Type::ConstantArray:
3468 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003469 MarkUsedTemplateParameters(SemaRef,
3470 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003471 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003472 break;
3473
3474 case Type::Vector:
3475 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003476 MarkUsedTemplateParameters(SemaRef,
3477 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003478 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003479 break;
3480
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003481 case Type::DependentSizedExtVector: {
3482 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003483 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003484 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003485 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003486 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003487 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003488 break;
3489 }
3490
Douglas Gregor031a5882009-06-13 00:26:55 +00003491 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003492 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003493 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003494 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003495 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003496 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003497 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003498 break;
3499 }
3500
Douglas Gregored9c0f92009-10-29 00:04:11 +00003501 case Type::TemplateTypeParm: {
3502 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3503 if (TTP->getDepth() == Depth)
3504 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003505 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003506 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003507
John McCall31f17ec2010-04-27 00:57:59 +00003508 case Type::InjectedClassName:
3509 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3510 // fall through
3511
Douglas Gregor031a5882009-06-13 00:26:55 +00003512 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003513 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003514 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003515 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003516 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003517
3518 // C++0x [temp.deduct.type]p9:
3519 // If the template argument list of P contains a pack expansion that is not
3520 // the last template argument, the entire template argument list is a
3521 // non-deduced context.
3522 if (OnlyDeduced &&
3523 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3524 break;
3525
Douglas Gregore73bb602009-09-14 21:25:05 +00003526 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003527 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3528 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003529 break;
3530 }
3531
Douglas Gregore73bb602009-09-14 21:25:05 +00003532 case Type::Complex:
3533 if (!OnlyDeduced)
3534 MarkUsedTemplateParameters(SemaRef,
3535 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003536 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003537 break;
3538
Douglas Gregor4714c122010-03-31 17:34:00 +00003539 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003540 if (!OnlyDeduced)
3541 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003542 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003543 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003544 break;
3545
John McCall33500952010-06-11 00:33:02 +00003546 case Type::DependentTemplateSpecialization: {
3547 const DependentTemplateSpecializationType *Spec
3548 = cast<DependentTemplateSpecializationType>(T);
3549 if (!OnlyDeduced)
3550 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3551 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003552
3553 // C++0x [temp.deduct.type]p9:
3554 // If the template argument list of P contains a pack expansion that is not
3555 // the last template argument, the entire template argument list is a
3556 // non-deduced context.
3557 if (OnlyDeduced &&
3558 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3559 break;
3560
John McCall33500952010-06-11 00:33:02 +00003561 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3562 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3563 Used);
3564 break;
3565 }
3566
John McCallad5e7382010-03-01 23:49:17 +00003567 case Type::TypeOf:
3568 if (!OnlyDeduced)
3569 MarkUsedTemplateParameters(SemaRef,
3570 cast<TypeOfType>(T)->getUnderlyingType(),
3571 OnlyDeduced, Depth, Used);
3572 break;
3573
3574 case Type::TypeOfExpr:
3575 if (!OnlyDeduced)
3576 MarkUsedTemplateParameters(SemaRef,
3577 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3578 OnlyDeduced, Depth, Used);
3579 break;
3580
3581 case Type::Decltype:
3582 if (!OnlyDeduced)
3583 MarkUsedTemplateParameters(SemaRef,
3584 cast<DecltypeType>(T)->getUnderlyingExpr(),
3585 OnlyDeduced, Depth, Used);
3586 break;
3587
Douglas Gregor7536dd52010-12-20 02:24:11 +00003588 case Type::PackExpansion:
3589 MarkUsedTemplateParameters(SemaRef,
3590 cast<PackExpansionType>(T)->getPattern(),
3591 OnlyDeduced, Depth, Used);
3592 break;
3593
Douglas Gregore73bb602009-09-14 21:25:05 +00003594 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003595 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003596 case Type::VariableArray:
3597 case Type::FunctionNoProto:
3598 case Type::Record:
3599 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003600 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003601 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003602 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003603 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003604#define TYPE(Class, Base)
3605#define ABSTRACT_TYPE(Class, Base)
3606#define DEPENDENT_TYPE(Class, Base)
3607#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3608#include "clang/AST/TypeNodes.def"
3609 break;
3610 }
3611}
3612
Douglas Gregore73bb602009-09-14 21:25:05 +00003613/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003614/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003615static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003616MarkUsedTemplateParameters(Sema &SemaRef,
3617 const TemplateArgument &TemplateArg,
3618 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003619 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003620 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003621 switch (TemplateArg.getKind()) {
3622 case TemplateArgument::Null:
3623 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003624 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003625 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Douglas Gregor031a5882009-06-13 00:26:55 +00003627 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003628 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003629 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003630 break;
3631
Douglas Gregor788cd062009-11-11 01:00:40 +00003632 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003633 case TemplateArgument::TemplateExpansion:
3634 MarkUsedTemplateParameters(SemaRef,
3635 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003636 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003637 break;
3638
3639 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003640 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003641 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003642 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003643
Anders Carlssond01b1da2009-06-15 17:04:53 +00003644 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003645 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3646 PEnd = TemplateArg.pack_end();
3647 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003648 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003649 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003650 }
3651}
3652
3653/// \brief Mark the template parameters can be deduced by the given
3654/// template argument list.
3655///
3656/// \param TemplateArgs the template argument list from which template
3657/// parameters will be deduced.
3658///
3659/// \param Deduced a bit vector whose elements will be set to \c true
3660/// to indicate when the corresponding template parameter will be
3661/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003662void
Douglas Gregore73bb602009-09-14 21:25:05 +00003663Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003664 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003665 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003666 // C++0x [temp.deduct.type]p9:
3667 // If the template argument list of P contains a pack expansion that is not
3668 // the last template argument, the entire template argument list is a
3669 // non-deduced context.
3670 if (OnlyDeduced &&
3671 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3672 return;
3673
Douglas Gregor031a5882009-06-13 00:26:55 +00003674 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003675 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3676 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003677}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003678
3679/// \brief Marks all of the template parameters that will be deduced by a
3680/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003681void
3682Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3683 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003684 TemplateParameterList *TemplateParams
3685 = FunctionTemplate->getTemplateParameters();
3686 Deduced.clear();
3687 Deduced.resize(TemplateParams->size());
3688
3689 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3690 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3691 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003692 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003693}