blob: 333eb32293adb8e2a23f15c797f51621e466156b [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 Gregor77d6bb92011-01-11 22:21:24 +000083 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:
John McCall62c28c82011-01-18 07:41:22 +0000479 case Type::TemplateTypeParm:
John McCallcd05e812010-08-28 22:14:41 +0000480 return true;
481
482 case Type::ConstantArray:
483 case Type::IncompleteArray:
484 case Type::VariableArray:
485 case Type::DependentSizedArray:
486 return IsPossiblyOpaquelyQualifiedType(
487 cast<ArrayType>(T)->getElementType());
488
489 default:
490 return false;
491 }
492}
493
Douglas Gregord3731192011-01-10 07:32:04 +0000494/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000495static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000496getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000497 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
498 return std::make_pair(TTP->getDepth(), TTP->getIndex());
499
500 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
501 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
502
503 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
504 return std::make_pair(TTP->getDepth(), TTP->getIndex());
505}
506
Douglas Gregord3731192011-01-10 07:32:04 +0000507/// \brief Retrieve the depth and index of an unexpanded parameter pack.
508static std::pair<unsigned, unsigned>
509getDepthAndIndex(UnexpandedParameterPack UPP) {
510 if (const TemplateTypeParmType *TTP
511 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
512 return std::make_pair(TTP->getDepth(), TTP->getIndex());
513
514 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
515}
516
Douglas Gregor603cfb42011-01-05 23:12:31 +0000517/// \brief Helper function to build a TemplateParameter when we don't
518/// know its type statically.
519static TemplateParameter makeTemplateParameter(Decl *D) {
520 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
521 return TemplateParameter(TTP);
522 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
523 return TemplateParameter(NTTP);
524
525 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
526}
527
Douglas Gregor54293852011-01-10 17:35:05 +0000528/// \brief Prepare to perform template argument deduction for all of the
529/// arguments in a set of argument packs.
530static void PrepareArgumentPackDeduction(Sema &S,
531 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
532 const llvm::SmallVectorImpl<unsigned> &PackIndices,
533 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
534 llvm::SmallVectorImpl<
535 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
536 // Save the deduced template arguments for each parameter pack expanded
537 // by this pack expansion, then clear out the deduction.
538 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
539 // Save the previously-deduced argument pack, then clear it out so that we
540 // can deduce a new argument pack.
541 SavedPacks[I] = Deduced[PackIndices[I]];
542 Deduced[PackIndices[I]] = TemplateArgument();
543
544 // If the template arugment pack was explicitly specified, add that to
545 // the set of deduced arguments.
546 const TemplateArgument *ExplicitArgs;
547 unsigned NumExplicitArgs;
548 if (NamedDecl *PartiallySubstitutedPack
549 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
550 &ExplicitArgs,
551 &NumExplicitArgs)) {
552 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
553 NewlyDeducedPacks[I].append(ExplicitArgs,
554 ExplicitArgs + NumExplicitArgs);
555 }
556 }
557}
558
Douglas Gregor0216f812011-01-10 17:53:52 +0000559/// \brief Finish template argument deduction for a set of argument packs,
560/// producing the argument packs and checking for consistency with prior
561/// deductions.
562static Sema::TemplateDeductionResult
563FinishArgumentPackDeduction(Sema &S,
564 TemplateParameterList *TemplateParams,
565 bool HasAnyArguments,
566 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
567 const llvm::SmallVectorImpl<unsigned> &PackIndices,
568 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
569 llvm::SmallVectorImpl<
570 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
571 TemplateDeductionInfo &Info) {
572 // Build argument packs for each of the parameter packs expanded by this
573 // pack expansion.
574 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
575 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
576 // We were not able to deduce anything for this parameter pack,
577 // so just restore the saved argument pack.
578 Deduced[PackIndices[I]] = SavedPacks[I];
579 continue;
580 }
581
582 DeducedTemplateArgument NewPack;
583
584 if (NewlyDeducedPacks[I].empty()) {
585 // If we deduced an empty argument pack, create it now.
586 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
587 } else {
588 TemplateArgument *ArgumentPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000589 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
Douglas Gregor0216f812011-01-10 17:53:52 +0000590 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
591 ArgumentPack);
592 NewPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000593 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
594 NewlyDeducedPacks[I].size()),
595 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
Douglas Gregor0216f812011-01-10 17:53:52 +0000596 }
597
598 DeducedTemplateArgument Result
599 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
600 if (Result.isNull()) {
601 Info.Param
602 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
603 Info.FirstArg = SavedPacks[I];
604 Info.SecondArg = NewPack;
605 return Sema::TDK_Inconsistent;
606 }
607
608 Deduced[PackIndices[I]] = Result;
609 }
610
611 return Sema::TDK_Success;
612}
613
Douglas Gregor603cfb42011-01-05 23:12:31 +0000614/// \brief Deduce the template arguments by comparing the list of parameter
615/// types to the list of argument types, as in the parameter-type-lists of
616/// function types (C++ [temp.deduct.type]p10).
617///
618/// \param S The semantic analysis object within which we are deducing
619///
620/// \param TemplateParams The template parameters that we are deducing
621///
622/// \param Params The list of parameter types
623///
624/// \param NumParams The number of types in \c Params
625///
626/// \param Args The list of argument types
627///
628/// \param NumArgs The number of types in \c Args
629///
630/// \param Info information about the template argument deduction itself
631///
632/// \param Deduced the deduced template arguments
633///
634/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
635/// how template argument deduction is performed.
636///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000637/// \param PartialOrdering If true, we are performing template argument
638/// deduction for during partial ordering for a call
639/// (C++0x [temp.deduct.partial]).
640///
641/// \param QualifierComparisons If we're performing template argument deduction
642/// in the context of partial ordering, the set of qualifier comparisons.
643///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000644/// \returns the result of template argument deduction so far. Note that a
645/// "success" result means that template argument deduction has not yet failed,
646/// but it may still fail, later, for other reasons.
647static Sema::TemplateDeductionResult
648DeduceTemplateArguments(Sema &S,
649 TemplateParameterList *TemplateParams,
650 const QualType *Params, unsigned NumParams,
651 const QualType *Args, unsigned NumArgs,
652 TemplateDeductionInfo &Info,
653 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000654 unsigned TDF,
655 bool PartialOrdering = false,
656 llvm::SmallVectorImpl<DeductionQualifierComparison> *
657 QualifierComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000658 // Fast-path check to see if we have too many/too few arguments.
659 if (NumParams != NumArgs &&
660 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
661 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000662 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000663
664 // C++0x [temp.deduct.type]p10:
665 // Similarly, if P has a form that contains (T), then each parameter type
666 // Pi of the respective parameter-type- list of P is compared with the
667 // corresponding parameter type Ai of the corresponding parameter-type-list
668 // of A. [...]
669 unsigned ArgIdx = 0, ParamIdx = 0;
670 for (; ParamIdx != NumParams; ++ParamIdx) {
671 // Check argument types.
672 const PackExpansionType *Expansion
673 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
674 if (!Expansion) {
675 // Simple case: compare the parameter and argument types at this point.
676
677 // Make sure we have an argument.
678 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000679 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000680
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000681 if (isa<PackExpansionType>(Args[ArgIdx])) {
682 // C++0x [temp.deduct.type]p22:
683 // If the original function parameter associated with A is a function
684 // parameter pack and the function parameter associated with P is not
685 // a function parameter pack, then template argument deduction fails.
686 return Sema::TDK_NonDeducedMismatch;
687 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000688
Douglas Gregor603cfb42011-01-05 23:12:31 +0000689 if (Sema::TemplateDeductionResult Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000690 = DeduceTemplateArguments(S, TemplateParams,
691 Params[ParamIdx],
692 Args[ArgIdx],
693 Info, Deduced, TDF,
694 PartialOrdering,
695 QualifierComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000696 return Result;
697
698 ++ArgIdx;
699 continue;
700 }
701
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000702 // C++0x [temp.deduct.type]p5:
703 // The non-deduced contexts are:
704 // - A function parameter pack that does not occur at the end of the
705 // parameter-declaration-clause.
706 if (ParamIdx + 1 < NumParams)
707 return Sema::TDK_Success;
708
Douglas Gregor603cfb42011-01-05 23:12:31 +0000709 // C++0x [temp.deduct.type]p10:
710 // If the parameter-declaration corresponding to Pi is a function
711 // parameter pack, then the type of its declarator- id is compared with
712 // each remaining parameter type in the parameter-type-list of A. Each
713 // comparison deduces template arguments for subsequent positions in the
714 // template parameter packs expanded by the function parameter pack.
715
716 // Compute the set of template parameter indices that correspond to
717 // parameter packs expanded by the pack expansion.
718 llvm::SmallVector<unsigned, 2> PackIndices;
719 QualType Pattern = Expansion->getPattern();
720 {
721 llvm::BitVector SawIndices(TemplateParams->size());
722 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
723 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
724 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
725 unsigned Depth, Index;
726 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
727 if (Depth == 0 && !SawIndices[Index]) {
728 SawIndices[Index] = true;
729 PackIndices.push_back(Index);
730 }
731 }
732 }
733 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
734
Douglas Gregord3731192011-01-10 07:32:04 +0000735 // Keep track of the deduced template arguments for each parameter pack
736 // expanded by this pack expansion (the outer index) and for each
737 // template argument (the inner SmallVectors).
738 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
739 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000740 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000741 SavedPacks(PackIndices.size());
742 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
743 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000744
Douglas Gregor603cfb42011-01-05 23:12:31 +0000745 bool HasAnyArguments = false;
746 for (; ArgIdx < NumArgs; ++ArgIdx) {
747 HasAnyArguments = true;
748
749 // Deduce template arguments from the pattern.
750 if (Sema::TemplateDeductionResult Result
751 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000752 Info, Deduced, PartialOrdering,
753 QualifierComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000754 return Result;
755
756 // Capture the deduced template arguments for each parameter pack expanded
757 // by this pack expansion, add them to the list of arguments we've deduced
758 // for that pack, then clear out the deduced argument.
759 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
760 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
761 if (!DeducedArg.isNull()) {
762 NewlyDeducedPacks[I].push_back(DeducedArg);
763 DeducedArg = DeducedTemplateArgument();
764 }
765 }
766 }
767
768 // Build argument packs for each of the parameter packs expanded by this
769 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000770 if (Sema::TemplateDeductionResult Result
771 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
772 Deduced, PackIndices, SavedPacks,
773 NewlyDeducedPacks, Info))
774 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000775 }
776
777 // Make sure we don't have any extra arguments.
778 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000779 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000780
781 return Sema::TDK_Success;
782}
783
Douglas Gregor500d3312009-06-26 18:27:22 +0000784/// \brief Deduce the template arguments by comparing the parameter type and
785/// the argument type (C++ [temp.deduct.type]).
786///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000787/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000788///
789/// \param TemplateParams the template parameters that we are deducing
790///
791/// \param ParamIn the parameter type
792///
793/// \param ArgIn the argument type
794///
795/// \param Info information about the template argument deduction itself
796///
797/// \param Deduced the deduced template arguments
798///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000799/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000800/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000801///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000802/// \param PartialOrdering Whether we're performing template argument deduction
803/// in the context of partial ordering (C++0x [temp.deduct.partial]).
804///
805/// \param QualifierComparisons If we're performing template argument deduction
806/// in the context of partial ordering, the set of qualifier comparisons.
807///
Douglas Gregor500d3312009-06-26 18:27:22 +0000808/// \returns the result of template argument deduction so far. Note that a
809/// "success" result means that template argument deduction has not yet failed,
810/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000811static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000812DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000813 TemplateParameterList *TemplateParams,
814 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000815 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000816 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000817 unsigned TDF,
818 bool PartialOrdering,
819 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000820 // We only want to look at the canonical types, since typedefs and
821 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000822 QualType Param = S.Context.getCanonicalType(ParamIn);
823 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000824
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000825 // If the argument type is a pack expansion, look at its pattern.
826 // This isn't explicitly called out
827 if (const PackExpansionType *ArgExpansion
828 = dyn_cast<PackExpansionType>(Arg))
829 Arg = ArgExpansion->getPattern();
830
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000831 if (PartialOrdering) {
832 // C++0x [temp.deduct.partial]p5:
833 // Before the partial ordering is done, certain transformations are
834 // performed on the types used for partial ordering:
835 // - If P is a reference type, P is replaced by the type referred to.
836 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
837 if (ParamRef)
838 Param = ParamRef->getPointeeType();
839
840 // - If A is a reference type, A is replaced by the type referred to.
841 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
842 if (ArgRef)
843 Arg = ArgRef->getPointeeType();
844
845 if (QualifierComparisons && ParamRef && ArgRef) {
846 // C++0x [temp.deduct.partial]p6:
847 // If both P and A were reference types (before being replaced with the
848 // type referred to above), determine which of the two types (if any) is
849 // more cv-qualified than the other; otherwise the types are considered
850 // to be equally cv-qualified for partial ordering purposes. The result
851 // of this determination will be used below.
852 //
853 // We save this information for later, using it only when deduction
854 // succeeds in both directions.
855 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
856 if (Param.isMoreQualifiedThan(Arg))
857 QualifierResult = ParamMoreQualified;
858 else if (Arg.isMoreQualifiedThan(Param))
859 QualifierResult = ArgMoreQualified;
860 QualifierComparisons->push_back(QualifierResult);
861 }
862
863 // C++0x [temp.deduct.partial]p7:
864 // Remove any top-level cv-qualifiers:
865 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
866 // version of P.
867 Param = Param.getUnqualifiedType();
868 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
869 // version of A.
870 Arg = Arg.getUnqualifiedType();
871 } else {
872 // C++0x [temp.deduct.call]p4 bullet 1:
873 // - If the original P is a reference type, the deduced A (i.e., the type
874 // referred to by the reference) can be more cv-qualified than the
875 // transformed A.
876 if (TDF & TDF_ParamWithReferenceType) {
877 Qualifiers Quals;
878 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
879 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall62c28c82011-01-18 07:41:22 +0000880 Arg.getCVRQualifiers());
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000881 Param = S.Context.getQualifiedType(UnqualParam, Quals);
882 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000883 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000884
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000885 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000886 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000887 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000888 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000889
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000890 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000891 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000892
Douglas Gregor199d9912009-06-05 00:53:49 +0000893 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000894 // A template type argument T, a template template argument TT or a
895 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000896 // the following forms:
897 //
898 // T
899 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000900 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000901 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000902 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000903 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000905 // If the argument type is an array type, move the qualifiers up to the
906 // top level, so they can be matched with the qualifiers on the parameter.
907 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000908 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000909 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000910 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000911 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000912 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000913 RecanonicalizeArg = true;
914 }
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000917 // The argument type can not be less qualified than the parameter
918 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000919 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000920 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000921 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000922 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000923 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000924 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000925
926 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000927 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000928 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000929
930 // local manipulation is okay because it's canonical
931 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000932 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000933 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000935 DeducedTemplateArgument NewDeduced(DeducedType);
936 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
937 Deduced[Index],
938 NewDeduced);
939 if (Result.isNull()) {
940 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
941 Info.FirstArg = Deduced[Index];
942 Info.SecondArg = NewDeduced;
943 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000944 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000945
946 Deduced[Index] = Result;
947 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000948 }
949
Douglas Gregorf67875d2009-06-12 18:26:56 +0000950 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000951 Info.FirstArg = TemplateArgument(ParamIn);
952 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000953
Douglas Gregor0bc15d92011-01-14 05:11:40 +0000954 // If the parameter is an already-substituted template parameter
955 // pack, do nothing: we don't know which of its arguments to look
956 // at, so we have to wait until all of the parameter packs in this
957 // expansion have arguments.
958 if (isa<SubstTemplateTypeParmPackType>(Param))
959 return Sema::TDK_Success;
960
Douglas Gregor508f1c82009-06-26 23:10:12 +0000961 // Check the cv-qualifiers on the parameter and argument types.
962 if (!(TDF & TDF_IgnoreQualifiers)) {
963 if (TDF & TDF_ParamWithReferenceType) {
964 if (Param.isMoreQualifiedThan(Arg))
965 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000966 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000967 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000968 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000969 }
970 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000971
Douglas Gregord560d502009-06-04 00:21:18 +0000972 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000973 // No deduction possible for these types
974 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000975 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Douglas Gregor199d9912009-06-05 00:53:49 +0000977 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000978 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000979 QualType PointeeType;
980 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
981 PointeeType = PointerArg->getPointeeType();
982 } else if (const ObjCObjectPointerType *PointerArg
983 = Arg->getAs<ObjCObjectPointerType>()) {
984 PointeeType = PointerArg->getPointeeType();
985 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000986 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000987 }
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregor41128772009-06-26 23:27:24 +0000989 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000990 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000991 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000992 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000993 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Douglas Gregor199d9912009-06-05 00:53:49 +0000996 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000997 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000998 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000999 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001000 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001002 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001003 cast<LValueReferenceType>(Param)->getPointeeType(),
1004 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001005 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001006 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001007
Douglas Gregor199d9912009-06-05 00:53:49 +00001008 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +00001009 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001010 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001011 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001012 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001014 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001015 cast<RValueReferenceType>(Param)->getPointeeType(),
1016 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001017 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregor199d9912009-06-05 00:53:49 +00001020 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001021 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001022 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001023 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001024 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001025 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001026
John McCalle4f26e52010-08-19 00:20:19 +00001027 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001028 return DeduceTemplateArguments(S, TemplateParams,
1029 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001030 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001031 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001032 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001033
1034 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001035 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001036 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001037 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001038 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001039 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
1041 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001042 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001043 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001044 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
John McCalle4f26e52010-08-19 00:20:19 +00001046 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001047 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001048 ConstantArrayParm->getElementType(),
1049 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001050 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001051 }
1052
Douglas Gregor199d9912009-06-05 00:53:49 +00001053 // type [i]
1054 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001055 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001056 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001057 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
John McCalle4f26e52010-08-19 00:20:19 +00001059 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1060
Douglas Gregor199d9912009-06-05 00:53:49 +00001061 // Check the element type of the arrays
1062 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001063 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001064 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001065 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001066 DependentArrayParm->getElementType(),
1067 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001068 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001069 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregor199d9912009-06-05 00:53:49 +00001071 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001072 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001073 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1074 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001075 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
1077 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001078 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001079 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001080 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001081 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001082 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1083 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001084 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1085 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001086 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001087 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001088 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001089 if (const DependentSizedArrayType *DependentArrayArg
1090 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001091 if (DependentArrayArg->getSizeExpr())
1092 return DeduceNonTypeTemplateArgument(S, NTTP,
1093 DependentArrayArg->getSizeExpr(),
1094 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregor199d9912009-06-05 00:53:49 +00001096 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001097 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001098 }
Mike Stump1eb44332009-09-09 15:08:12 +00001099
1100 // type(*)(T)
1101 // T(*)()
1102 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001103 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001104 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001105 dyn_cast<FunctionProtoType>(Arg);
1106 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001107 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001108
1109 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001110 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001111
Mike Stump1eb44332009-09-09 15:08:12 +00001112 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001113 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001114 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001116 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001117 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001118
Anders Carlssona27fad52009-06-08 15:19:08 +00001119 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001120 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001121 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001122 FunctionProtoParam->getResultType(),
1123 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001124 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001125 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Douglas Gregor603cfb42011-01-05 23:12:31 +00001127 return DeduceTemplateArguments(S, TemplateParams,
1128 FunctionProtoParam->arg_type_begin(),
1129 FunctionProtoParam->getNumArgs(),
1130 FunctionProtoArg->arg_type_begin(),
1131 FunctionProtoArg->getNumArgs(),
1132 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001133 }
Mike Stump1eb44332009-09-09 15:08:12 +00001134
John McCall3cb0ebd2010-03-10 03:28:59 +00001135 case Type::InjectedClassName: {
1136 // Treat a template's injected-class-name as if the template
1137 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001138 Param = cast<InjectedClassNameType>(Param)
1139 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001140 assert(isa<TemplateSpecializationType>(Param) &&
1141 "injected class name is not a template specialization type");
1142 // fall through
1143 }
1144
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001145 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001146 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001147 // TT<T>
1148 // TT<i>
1149 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001150 case Type::TemplateSpecialization: {
1151 const TemplateSpecializationType *SpecParam
1152 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001154 // Try to deduce template arguments from the template-id.
1155 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001156 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001157 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001159 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001160 // C++ [temp.deduct.call]p3b3:
1161 // If P is a class, and P has the form template-id, then A can be a
1162 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001163 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001164 // class pointed to by the deduced A.
1165 //
1166 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001167 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001168 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001169 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1170 // We cannot inspect base classes as part of deduction when the type
1171 // is incomplete, so either instantiate any templates necessary to
1172 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001173 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001174 return Result;
1175
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001176 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001177 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001178 // ToVisit is our stack of records that we still need to visit.
1179 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1180 llvm::SmallVector<const RecordType *, 8> ToVisit;
1181 ToVisit.push_back(RecordT);
1182 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001183 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1184 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001185 while (!ToVisit.empty()) {
1186 // Retrieve the next class in the inheritance hierarchy.
1187 const RecordType *NextT = ToVisit.back();
1188 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001190 // If we have already seen this type, skip it.
1191 if (!Visited.insert(NextT))
1192 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001194 // If this is a base class, try to perform template argument
1195 // deduction from it.
1196 if (NextT != RecordT) {
1197 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001198 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001199 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001201 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001202 // note that we had some success. Otherwise, ignore any deductions
1203 // from this base class.
1204 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001205 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001206 DeducedOrig = Deduced;
1207 }
1208 else
1209 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001212 // Visit base classes
1213 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1214 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1215 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001216 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001217 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001218 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001219 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001220 }
1221 }
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001223 if (Successful)
1224 return Sema::TDK_Success;
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001227 }
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001229 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001230 }
1231
Douglas Gregor637a4092009-06-10 23:47:09 +00001232 // T type::*
1233 // T T::*
1234 // T (type::*)()
1235 // type (T::*)()
1236 // type (type::*)(T)
1237 // type (T::*)(T)
1238 // T (type::*)(T)
1239 // T (T::*)()
1240 // T (T::*)(T)
1241 case Type::MemberPointer: {
1242 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1243 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1244 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001245 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001246
Douglas Gregorf67875d2009-06-12 18:26:56 +00001247 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001248 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001249 MemPtrParam->getPointeeType(),
1250 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001251 Info, Deduced,
1252 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001253 return Result;
1254
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001255 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001256 QualType(MemPtrParam->getClass(), 0),
1257 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001258 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001259 }
1260
Anders Carlsson9a917e42009-06-12 22:56:54 +00001261 // (clang extension)
1262 //
Mike Stump1eb44332009-09-09 15:08:12 +00001263 // type(^)(T)
1264 // T(^)()
1265 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001266 case Type::BlockPointer: {
1267 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1268 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Anders Carlsson859ba502009-06-12 16:23:10 +00001270 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001271 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001273 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001274 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001275 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001276 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001277 }
1278
Douglas Gregor637a4092009-06-10 23:47:09 +00001279 case Type::TypeOfExpr:
1280 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001281 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001282 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001283 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001284
Douglas Gregord560d502009-06-04 00:21:18 +00001285 default:
1286 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001287 }
1288
1289 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001290 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001291}
1292
Douglas Gregorf67875d2009-06-12 18:26:56 +00001293static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001294DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001295 TemplateParameterList *TemplateParams,
1296 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001297 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001298 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001299 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001300 // If the template argument is a pack expansion, perform template argument
1301 // deduction against the pattern of that expansion. This only occurs during
1302 // partial ordering.
1303 if (Arg.isPackExpansion())
1304 Arg = Arg.getPackExpansionPattern();
1305
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001306 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001307 case TemplateArgument::Null:
1308 assert(false && "Null template argument in parameter list");
1309 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001310
1311 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001312 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001313 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001314 Arg.getAsType(), Info, Deduced, 0);
1315 Info.FirstArg = Param;
1316 Info.SecondArg = Arg;
1317 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001318
Douglas Gregor788cd062009-11-11 01:00:40 +00001319 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001320 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001321 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001322 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001323 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001324 Info.FirstArg = Param;
1325 Info.SecondArg = Arg;
1326 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001327
1328 case TemplateArgument::TemplateExpansion:
1329 llvm_unreachable("caller should handle pack expansions");
1330 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001331
Douglas Gregor199d9912009-06-05 00:53:49 +00001332 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001333 if (Arg.getKind() == TemplateArgument::Declaration &&
1334 Param.getAsDecl()->getCanonicalDecl() ==
1335 Arg.getAsDecl()->getCanonicalDecl())
1336 return Sema::TDK_Success;
1337
Douglas Gregorf67875d2009-06-12 18:26:56 +00001338 Info.FirstArg = Param;
1339 Info.SecondArg = Arg;
1340 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Douglas Gregor199d9912009-06-05 00:53:49 +00001342 case TemplateArgument::Integral:
1343 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001344 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001345 return Sema::TDK_Success;
1346
1347 Info.FirstArg = Param;
1348 Info.SecondArg = Arg;
1349 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001350 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001351
1352 if (Arg.getKind() == TemplateArgument::Expression) {
1353 Info.FirstArg = Param;
1354 Info.SecondArg = Arg;
1355 return Sema::TDK_NonDeducedMismatch;
1356 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001357
Douglas Gregorf67875d2009-06-12 18:26:56 +00001358 Info.FirstArg = Param;
1359 Info.SecondArg = Arg;
1360 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregor199d9912009-06-05 00:53:49 +00001362 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001363 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001364 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1365 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001366 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001367 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001368 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001369 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001370 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001371 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001372 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001373 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001374 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001375 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001376 Info, Deduced);
1377
Douglas Gregorf67875d2009-06-12 18:26:56 +00001378 Info.FirstArg = Param;
1379 Info.SecondArg = Arg;
1380 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Douglas Gregor199d9912009-06-05 00:53:49 +00001383 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001384 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001385 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001386 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001387 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Douglas Gregorf67875d2009-06-12 18:26:56 +00001390 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001391}
1392
Douglas Gregor20a55e22010-12-22 18:17:10 +00001393/// \brief Determine whether there is a template argument to be used for
1394/// deduction.
1395///
1396/// This routine "expands" argument packs in-place, overriding its input
1397/// parameters so that \c Args[ArgIdx] will be the available template argument.
1398///
1399/// \returns true if there is another template argument (which will be at
1400/// \c Args[ArgIdx]), false otherwise.
1401static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1402 unsigned &ArgIdx,
1403 unsigned &NumArgs) {
1404 if (ArgIdx == NumArgs)
1405 return false;
1406
1407 const TemplateArgument &Arg = Args[ArgIdx];
1408 if (Arg.getKind() != TemplateArgument::Pack)
1409 return true;
1410
1411 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1412 Args = Arg.pack_begin();
1413 NumArgs = Arg.pack_size();
1414 ArgIdx = 0;
1415 return ArgIdx < NumArgs;
1416}
1417
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001418/// \brief Determine whether the given set of template arguments has a pack
1419/// expansion that is not the last template argument.
1420static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1421 unsigned NumArgs) {
1422 unsigned ArgIdx = 0;
1423 while (ArgIdx < NumArgs) {
1424 const TemplateArgument &Arg = Args[ArgIdx];
1425
1426 // Unwrap argument packs.
1427 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1428 Args = Arg.pack_begin();
1429 NumArgs = Arg.pack_size();
1430 ArgIdx = 0;
1431 continue;
1432 }
1433
1434 ++ArgIdx;
1435 if (ArgIdx == NumArgs)
1436 return false;
1437
1438 if (Arg.isPackExpansion())
1439 return true;
1440 }
1441
1442 return false;
1443}
1444
Douglas Gregor20a55e22010-12-22 18:17:10 +00001445static Sema::TemplateDeductionResult
1446DeduceTemplateArguments(Sema &S,
1447 TemplateParameterList *TemplateParams,
1448 const TemplateArgument *Params, unsigned NumParams,
1449 const TemplateArgument *Args, unsigned NumArgs,
1450 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001451 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1452 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001453 // C++0x [temp.deduct.type]p9:
1454 // If the template argument list of P contains a pack expansion that is not
1455 // the last template argument, the entire template argument list is a
1456 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001457 if (hasPackExpansionBeforeEnd(Params, NumParams))
1458 return Sema::TDK_Success;
1459
Douglas Gregore02e2622010-12-22 21:19:48 +00001460 // C++0x [temp.deduct.type]p9:
1461 // If P has a form that contains <T> or <i>, then each argument Pi of the
1462 // respective template argument list P is compared with the corresponding
1463 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001464 unsigned ArgIdx = 0, ParamIdx = 0;
1465 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1466 ++ParamIdx) {
1467 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001468 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001469
1470 // Check whether we have enough arguments.
1471 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001472 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001473 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001474
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001475 if (Args[ArgIdx].isPackExpansion()) {
1476 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1477 // but applied to pack expansions that are template arguments.
1478 return Sema::TDK_NonDeducedMismatch;
1479 }
1480
Douglas Gregore02e2622010-12-22 21:19:48 +00001481 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001482 if (Sema::TemplateDeductionResult Result
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001483 = DeduceTemplateArguments(S, TemplateParams,
1484 Params[ParamIdx], Args[ArgIdx],
1485 Info, Deduced))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001486 return Result;
1487
1488 // Move to the next argument.
1489 ++ArgIdx;
1490 continue;
1491 }
1492
Douglas Gregore02e2622010-12-22 21:19:48 +00001493 // The parameter is a pack expansion.
1494
1495 // C++0x [temp.deduct.type]p9:
1496 // If Pi is a pack expansion, then the pattern of Pi is compared with
1497 // each remaining argument in the template argument list of A. Each
1498 // comparison deduces template arguments for subsequent positions in the
1499 // template parameter packs expanded by Pi.
1500 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1501
1502 // Compute the set of template parameter indices that correspond to
1503 // parameter packs expanded by the pack expansion.
1504 llvm::SmallVector<unsigned, 2> PackIndices;
1505 {
1506 llvm::BitVector SawIndices(TemplateParams->size());
1507 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1508 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1509 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1510 unsigned Depth, Index;
1511 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1512 if (Depth == 0 && !SawIndices[Index]) {
1513 SawIndices[Index] = true;
1514 PackIndices.push_back(Index);
1515 }
1516 }
1517 }
1518 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1519
1520 // FIXME: If there are no remaining arguments, we can bail out early
1521 // and set any deduced parameter packs to an empty argument pack.
1522 // The latter part of this is a (minor) correctness issue.
1523
1524 // Save the deduced template arguments for each parameter pack expanded
1525 // by this pack expansion, then clear out the deduction.
1526 llvm::SmallVector<DeducedTemplateArgument, 2>
1527 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001528 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1529 NewlyDeducedPacks(PackIndices.size());
1530 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1531 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001532
1533 // Keep track of the deduced template arguments for each parameter pack
1534 // expanded by this pack expansion (the outer index) and for each
1535 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001536 bool HasAnyArguments = false;
1537 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1538 HasAnyArguments = true;
1539
1540 // Deduce template arguments from the pattern.
1541 if (Sema::TemplateDeductionResult Result
1542 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1543 Info, Deduced))
1544 return Result;
1545
1546 // Capture the deduced template arguments for each parameter pack expanded
1547 // by this pack expansion, add them to the list of arguments we've deduced
1548 // for that pack, then clear out the deduced argument.
1549 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1550 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1551 if (!DeducedArg.isNull()) {
1552 NewlyDeducedPacks[I].push_back(DeducedArg);
1553 DeducedArg = DeducedTemplateArgument();
1554 }
1555 }
1556
1557 ++ArgIdx;
1558 }
1559
1560 // Build argument packs for each of the parameter packs expanded by this
1561 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001562 if (Sema::TemplateDeductionResult Result
1563 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1564 Deduced, PackIndices, SavedPacks,
1565 NewlyDeducedPacks, Info))
1566 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001567 }
1568
1569 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001570 if (NumberOfArgumentsMustMatch &&
1571 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001572 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001573
1574 return Sema::TDK_Success;
1575}
1576
Mike Stump1eb44332009-09-09 15:08:12 +00001577static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001578DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001579 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001580 const TemplateArgumentList &ParamList,
1581 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001582 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001583 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001584 return DeduceTemplateArguments(S, TemplateParams,
1585 ParamList.data(), ParamList.size(),
1586 ArgList.data(), ArgList.size(),
1587 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001588}
1589
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001590/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001591static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001592 const TemplateArgument &X,
1593 const TemplateArgument &Y) {
1594 if (X.getKind() != Y.getKind())
1595 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001597 switch (X.getKind()) {
1598 case TemplateArgument::Null:
1599 assert(false && "Comparing NULL template argument");
1600 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001602 case TemplateArgument::Type:
1603 return Context.getCanonicalType(X.getAsType()) ==
1604 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001606 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001607 return X.getAsDecl()->getCanonicalDecl() ==
1608 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregor788cd062009-11-11 01:00:40 +00001610 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001611 case TemplateArgument::TemplateExpansion:
1612 return Context.getCanonicalTemplateName(
1613 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1614 Context.getCanonicalTemplateName(
1615 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001616
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001617 case TemplateArgument::Integral:
1618 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Douglas Gregor788cd062009-11-11 01:00:40 +00001620 case TemplateArgument::Expression: {
1621 llvm::FoldingSetNodeID XID, YID;
1622 X.getAsExpr()->Profile(XID, Context, true);
1623 Y.getAsExpr()->Profile(YID, Context, true);
1624 return XID == YID;
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001627 case TemplateArgument::Pack:
1628 if (X.pack_size() != Y.pack_size())
1629 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
1631 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1632 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001633 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001634 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001635 if (!isSameTemplateArg(Context, *XP, *YP))
1636 return false;
1637
1638 return true;
1639 }
1640
1641 return false;
1642}
1643
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001644/// \brief Allocate a TemplateArgumentLoc where all locations have
1645/// been initialized to the given location.
1646///
1647/// \param S The semantic analysis object.
1648///
1649/// \param The template argument we are producing template argument
1650/// location information for.
1651///
1652/// \param NTTPType For a declaration template argument, the type of
1653/// the non-type template parameter that corresponds to this template
1654/// argument.
1655///
1656/// \param Loc The source location to use for the resulting template
1657/// argument.
1658static TemplateArgumentLoc
1659getTrivialTemplateArgumentLoc(Sema &S,
1660 const TemplateArgument &Arg,
1661 QualType NTTPType,
1662 SourceLocation Loc) {
1663 switch (Arg.getKind()) {
1664 case TemplateArgument::Null:
1665 llvm_unreachable("Can't get a NULL template argument here");
1666 break;
1667
1668 case TemplateArgument::Type:
1669 return TemplateArgumentLoc(Arg,
1670 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1671
1672 case TemplateArgument::Declaration: {
1673 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001674 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001675 .takeAs<Expr>();
1676 return TemplateArgumentLoc(TemplateArgument(E), E);
1677 }
1678
1679 case TemplateArgument::Integral: {
1680 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001681 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001682 return TemplateArgumentLoc(TemplateArgument(E), E);
1683 }
1684
1685 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001686 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1687
1688 case TemplateArgument::TemplateExpansion:
1689 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1690
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001691 case TemplateArgument::Expression:
1692 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1693
1694 case TemplateArgument::Pack:
1695 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1696 }
1697
1698 return TemplateArgumentLoc();
1699}
1700
1701
1702/// \brief Convert the given deduced template argument and add it to the set of
1703/// fully-converted template arguments.
1704static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1705 DeducedTemplateArgument Arg,
1706 NamedDecl *Template,
1707 QualType NTTPType,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001708 unsigned ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001709 TemplateDeductionInfo &Info,
1710 bool InFunctionTemplate,
1711 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1712 if (Arg.getKind() == TemplateArgument::Pack) {
1713 // This is a template argument pack, so check each of its arguments against
1714 // the template parameter.
1715 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1716 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001717 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001718 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001719 // When converting the deduced template argument, append it to the
1720 // general output list. We need to do this so that the template argument
1721 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001722 DeducedTemplateArgument InnerArg(*PA);
1723 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1724 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001725 NTTPType, PackedArgsBuilder.size(),
1726 Info, InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001727 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001728
1729 // Move the converted template argument into our argument pack.
1730 PackedArgsBuilder.push_back(Output.back());
1731 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001732 }
1733
1734 // Create the resulting argument pack.
Douglas Gregor203e6a32011-01-11 23:09:57 +00001735 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
1736 PackedArgsBuilder.data(),
1737 PackedArgsBuilder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001738 return false;
1739 }
1740
1741 // Convert the deduced template argument into a template
1742 // argument that we can check, almost as if the user had written
1743 // the template argument explicitly.
1744 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1745 Info.getLocation());
1746
1747 // Check the template argument, converting it as necessary.
1748 return S.CheckTemplateArgument(Param, ArgLoc,
1749 Template,
1750 Template->getLocation(),
1751 Template->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001752 ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001753 Output,
1754 InFunctionTemplate
1755 ? (Arg.wasDeducedFromArrayBound()
1756 ? Sema::CTAK_DeducedFromArrayBound
1757 : Sema::CTAK_Deduced)
1758 : Sema::CTAK_Specified);
1759}
1760
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001761/// Complete template argument deduction for a class template partial
1762/// specialization.
1763static Sema::TemplateDeductionResult
1764FinishTemplateArgumentDeduction(Sema &S,
1765 ClassTemplatePartialSpecializationDecl *Partial,
1766 const TemplateArgumentList &TemplateArgs,
1767 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001768 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001769 // Trap errors.
1770 Sema::SFINAETrap Trap(S);
1771
1772 Sema::ContextRAII SavedContext(S, Partial);
1773
1774 // C++ [temp.deduct.type]p2:
1775 // [...] or if any template argument remains neither deduced nor
1776 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001777 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001778 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1779 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001780 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001781 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001782 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001783 return Sema::TDK_Incomplete;
1784 }
1785
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001786 // We have deduced this argument, so it still needs to be
1787 // checked and converted.
1788
1789 // First, for a non-type template parameter type that is
1790 // initialized by a declaration, we need the type of the
1791 // corresponding non-type template parameter.
1792 QualType NTTPType;
1793 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001794 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001795 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001796 if (NTTPType->isDependentType()) {
1797 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1798 Builder.data(), Builder.size());
1799 NTTPType = S.SubstType(NTTPType,
1800 MultiLevelTemplateArgumentList(TemplateArgs),
1801 NTTP->getLocation(),
1802 NTTP->getDeclName());
1803 if (NTTPType.isNull()) {
1804 Info.Param = makeTemplateParameter(Param);
1805 // FIXME: These template arguments are temporary. Free them!
1806 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1807 Builder.data(),
1808 Builder.size()));
1809 return Sema::TDK_SubstitutionFailure;
1810 }
1811 }
1812 }
1813
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001814 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001815 Partial, NTTPType, 0, Info, false,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001816 Builder)) {
1817 Info.Param = makeTemplateParameter(Param);
1818 // FIXME: These template arguments are temporary. Free them!
1819 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1820 Builder.size()));
1821 return Sema::TDK_SubstitutionFailure;
1822 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001823 }
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001824
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001825 // Form the template argument list from the deduced template arguments.
1826 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001827 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1828 Builder.size());
1829
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001830 Info.reset(DeducedArgumentList);
1831
1832 // Substitute the deduced template arguments into the template
1833 // arguments of the class template partial specialization, and
1834 // verify that the instantiated template arguments are both valid
1835 // and are equivalent to the template arguments originally provided
1836 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001837 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001838 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1839 const TemplateArgumentLoc *PartialTemplateArgs
1840 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001841
1842 // Note that we don't provide the langle and rangle locations.
1843 TemplateArgumentListInfo InstArgs;
1844
Douglas Gregore02e2622010-12-22 21:19:48 +00001845 if (S.Subst(PartialTemplateArgs,
1846 Partial->getNumTemplateArgsAsWritten(),
1847 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1848 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1849 if (ParamIdx >= Partial->getTemplateParameters()->size())
1850 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1851
1852 Decl *Param
1853 = const_cast<NamedDecl *>(
1854 Partial->getTemplateParameters()->getParam(ParamIdx));
1855 Info.Param = makeTemplateParameter(Param);
1856 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1857 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001858 }
1859
Douglas Gregor910f8002010-11-07 23:05:16 +00001860 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001861 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001862 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001863 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001864
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001865 TemplateParameterList *TemplateParams
1866 = ClassTemplate->getTemplateParameters();
1867 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001868 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001869 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001870 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001871 Info.FirstArg = TemplateArgs[I];
1872 Info.SecondArg = InstArg;
1873 return Sema::TDK_NonDeducedMismatch;
1874 }
1875 }
1876
1877 if (Trap.hasErrorOccurred())
1878 return Sema::TDK_SubstitutionFailure;
1879
1880 return Sema::TDK_Success;
1881}
1882
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001883/// \brief Perform template argument deduction to determine whether
1884/// the given template arguments match the given class template
1885/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001886Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001887Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001888 const TemplateArgumentList &TemplateArgs,
1889 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001890 // C++ [temp.class.spec.match]p2:
1891 // A partial specialization matches a given actual template
1892 // argument list if the template arguments of the partial
1893 // specialization can be deduced from the actual template argument
1894 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001895 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001896 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001897 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001898 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001899 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001900 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001901 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001902 TemplateArgs, Info, Deduced))
1903 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001904
Douglas Gregor637a4092009-06-10 23:47:09 +00001905 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001906 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001907 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001908 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001909
Douglas Gregorbb260412009-06-14 08:02:22 +00001910 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001911 return Sema::TDK_SubstitutionFailure;
1912
1913 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1914 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001915}
Douglas Gregor031a5882009-06-13 00:26:55 +00001916
Douglas Gregor41128772009-06-26 23:27:24 +00001917/// \brief Determine whether the given type T is a simple-template-id type.
1918static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001919 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001920 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001921 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregor41128772009-06-26 23:27:24 +00001923 return false;
1924}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001925
1926/// \brief Substitute the explicitly-provided template arguments into the
1927/// given function template according to C++ [temp.arg.explicit].
1928///
1929/// \param FunctionTemplate the function template into which the explicit
1930/// template arguments will be substituted.
1931///
Mike Stump1eb44332009-09-09 15:08:12 +00001932/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001933/// arguments.
1934///
Mike Stump1eb44332009-09-09 15:08:12 +00001935/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936/// with the converted and checked explicit template arguments.
1937///
Mike Stump1eb44332009-09-09 15:08:12 +00001938/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001939/// parameters.
1940///
1941/// \param FunctionType if non-NULL, the result type of the function template
1942/// will also be instantiated and the pointed-to value will be updated with
1943/// the instantiated function type.
1944///
1945/// \param Info if substitution fails for any reason, this object will be
1946/// populated with more information about the failure.
1947///
1948/// \returns TDK_Success if substitution was successful, or some failure
1949/// condition.
1950Sema::TemplateDeductionResult
1951Sema::SubstituteExplicitTemplateArguments(
1952 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001953 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001954 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001955 llvm::SmallVectorImpl<QualType> &ParamTypes,
1956 QualType *FunctionType,
1957 TemplateDeductionInfo &Info) {
1958 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1959 TemplateParameterList *TemplateParams
1960 = FunctionTemplate->getTemplateParameters();
1961
John McCalld5532b62009-11-23 01:53:49 +00001962 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001963 // No arguments to substitute; just copy over the parameter types and
1964 // fill in the function type.
1965 for (FunctionDecl::param_iterator P = Function->param_begin(),
1966 PEnd = Function->param_end();
1967 P != PEnd;
1968 ++P)
1969 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Douglas Gregor83314aa2009-07-08 20:55:45 +00001971 if (FunctionType)
1972 *FunctionType = Function->getType();
1973 return TDK_Success;
1974 }
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor83314aa2009-07-08 20:55:45 +00001976 // Substitution of the explicit template arguments into a function template
1977 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001978 SFINAETrap Trap(*this);
1979
Douglas Gregor83314aa2009-07-08 20:55:45 +00001980 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001981 // Template arguments that are present shall be specified in the
1982 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001983 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001984 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001985 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
1987 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001988 // explicitly-specified template arguments against this function template,
1989 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001990 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001991 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001992 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1993 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001994 if (Inst)
1995 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Douglas Gregor83314aa2009-07-08 20:55:45 +00001997 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001998 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001999 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002000 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00002001 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002002 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00002003 if (Index >= TemplateParams->size())
2004 Index = TemplateParams->size() - 1;
2005 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002006 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00002007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Douglas Gregor83314aa2009-07-08 20:55:45 +00002009 // Form the template argument list from the explicitly-specified
2010 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002011 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002012 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002013 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00002014
John McCalldf41f182010-10-12 19:40:14 +00002015 // Template argument deduction and the final substitution should be
2016 // done in the context of the templated declaration. Explicit
2017 // argument substitution, on the other hand, needs to happen in the
2018 // calling context.
2019 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2020
Douglas Gregord3731192011-01-10 07:32:04 +00002021 // If we deduced template arguments for a template parameter pack,
2022 // note that the template argument pack is partially substituted and record
2023 // the explicit template arguments. They'll be used as part of deduction
2024 // for this template parameter pack.
Douglas Gregord3731192011-01-10 07:32:04 +00002025 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2026 const TemplateArgument &Arg = Builder[I];
2027 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregord3731192011-01-10 07:32:04 +00002028 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2029 TemplateParams->getParam(I),
2030 Arg.pack_begin(),
2031 Arg.pack_size());
2032 break;
2033 }
2034 }
2035
Douglas Gregor83314aa2009-07-08 20:55:45 +00002036 // Instantiate the types of each of the function parameters given the
2037 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00002038 if (SubstParmTypes(Function->getLocation(),
2039 Function->param_begin(), Function->getNumParams(),
2040 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2041 ParamTypes))
2042 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002043
2044 // If the caller wants a full function type back, instantiate the return
2045 // type and form that function type.
2046 if (FunctionType) {
2047 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00002048 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002049 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002050 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00002051
2052 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00002053 = SubstType(Proto->getResultType(),
2054 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2055 Function->getTypeSpecStartLoc(),
2056 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002057 if (ResultType.isNull() || Trap.hasErrorOccurred())
2058 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002059
2060 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002061 ParamTypes.data(), ParamTypes.size(),
2062 Proto->isVariadic(),
2063 Proto->getTypeQuals(),
2064 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002065 Function->getDeclName(),
2066 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002067 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2068 return TDK_SubstitutionFailure;
2069 }
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Douglas Gregor83314aa2009-07-08 20:55:45 +00002071 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002072 // Trailing template arguments that can be deduced (14.8.2) may be
2073 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002074 // template arguments can be deduced, they may all be omitted; in this
2075 // case, the empty template argument list <> itself may also be omitted.
2076 //
Douglas Gregord3731192011-01-10 07:32:04 +00002077 // Take all of the explicitly-specified arguments and put them into
2078 // the set of deduced template arguments. Explicitly-specified
2079 // parameter packs, however, will be set to NULL since the deduction
2080 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002081 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002082 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2083 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2084 if (Arg.getKind() == TemplateArgument::Pack)
2085 Deduced.push_back(DeducedTemplateArgument());
2086 else
2087 Deduced.push_back(Arg);
2088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor83314aa2009-07-08 20:55:45 +00002090 return TDK_Success;
2091}
2092
Mike Stump1eb44332009-09-09 15:08:12 +00002093/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002094/// checking the deduced template arguments for completeness and forming
2095/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002096Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002097Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00002098 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2099 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002100 FunctionDecl *&Specialization,
2101 TemplateDeductionInfo &Info) {
2102 TemplateParameterList *TemplateParams
2103 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Douglas Gregor83314aa2009-07-08 20:55:45 +00002105 // Template argument deduction for function templates in a SFINAE context.
2106 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002107 SFINAETrap Trap(*this);
2108
Douglas Gregor83314aa2009-07-08 20:55:45 +00002109 // Enter a new template instantiation context while we instantiate the
2110 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002111 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002112 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002113 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2114 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002115 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002116 return TDK_InstantiationDepth;
2117
John McCall96db3102010-04-29 01:18:58 +00002118 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002119
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002120 // C++ [temp.deduct.type]p2:
2121 // [...] or if any template argument remains neither deduced nor
2122 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002123 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002124 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2125 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002126
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002127 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002128 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002129 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002130 // argument, because it was explicitly-specified. Just record the
2131 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002132 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002133 continue;
2134 }
2135
2136 // We have deduced this argument, so it still needs to be
2137 // checked and converted.
2138
2139 // First, for a non-type template parameter type that is
2140 // initialized by a declaration, we need the type of the
2141 // corresponding non-type template parameter.
2142 QualType NTTPType;
2143 if (NonTypeTemplateParmDecl *NTTP
2144 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002145 NTTPType = NTTP->getType();
2146 if (NTTPType->isDependentType()) {
2147 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2148 Builder.data(), Builder.size());
2149 NTTPType = SubstType(NTTPType,
2150 MultiLevelTemplateArgumentList(TemplateArgs),
2151 NTTP->getLocation(),
2152 NTTP->getDeclName());
2153 if (NTTPType.isNull()) {
2154 Info.Param = makeTemplateParameter(Param);
2155 // FIXME: These template arguments are temporary. Free them!
2156 Info.reset(TemplateArgumentList::CreateCopy(Context,
2157 Builder.data(),
2158 Builder.size()));
2159 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002160 }
2161 }
2162 }
2163
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002164 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002165 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002166 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002167 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002168 // FIXME: These template arguments are temporary. Free them!
2169 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002170 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002171 return TDK_SubstitutionFailure;
2172 }
2173
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002174 continue;
2175 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002176
2177 // C++0x [temp.arg.explicit]p3:
2178 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2179 // be deduced to an empty sequence of template arguments.
2180 // FIXME: Where did the word "trailing" come from?
2181 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002182 // We may have had explicitly-specified template arguments for this
2183 // template parameter pack. If so, our empty deduction extends the
2184 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2185 const TemplateArgument *ExplicitArgs;
2186 unsigned NumExplicitArgs;
2187 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2188 &NumExplicitArgs)
2189 == Param)
2190 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2191 else
2192 Builder.push_back(TemplateArgument(0, 0));
2193
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002194 continue;
2195 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002196
2197 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002198 TemplateArgumentLoc DefArg
2199 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2200 FunctionTemplate->getLocation(),
2201 FunctionTemplate->getSourceRange().getEnd(),
2202 Param,
2203 Builder);
2204
2205 // If there was no default argument, deduction is incomplete.
2206 if (DefArg.getArgument().isNull()) {
2207 Info.Param = makeTemplateParameter(
2208 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2209 return TDK_Incomplete;
2210 }
2211
2212 // Check whether we can actually use the default argument.
2213 if (CheckTemplateArgument(Param, DefArg,
2214 FunctionTemplate,
2215 FunctionTemplate->getLocation(),
2216 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002217 0, Builder,
Douglas Gregor02024a92010-03-28 02:42:43 +00002218 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002219 Info.Param = makeTemplateParameter(
2220 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002221 // FIXME: These template arguments are temporary. Free them!
2222 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2223 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002224 return TDK_SubstitutionFailure;
2225 }
2226
2227 // If we get here, we successfully used the default template argument.
2228 }
2229
2230 // Form the template argument list from the deduced template arguments.
2231 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002232 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002233 Info.reset(DeducedArgumentList);
2234
Mike Stump1eb44332009-09-09 15:08:12 +00002235 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002236 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002237 DeclContext *Owner = FunctionTemplate->getDeclContext();
2238 if (FunctionTemplate->getFriendObjectKind())
2239 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002240 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002241 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002242 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002243 if (!Specialization)
2244 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregorf8825742009-09-15 18:26:13 +00002246 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2247 FunctionTemplate->getCanonicalDecl());
2248
Mike Stump1eb44332009-09-09 15:08:12 +00002249 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002250 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002251 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2252 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002253 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor83314aa2009-07-08 20:55:45 +00002255 // There may have been an error that did not prevent us from constructing a
2256 // declaration. Mark the declaration invalid and return with a substitution
2257 // failure.
2258 if (Trap.hasErrorOccurred()) {
2259 Specialization->setInvalidDecl(true);
2260 return TDK_SubstitutionFailure;
2261 }
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Douglas Gregor9b623632010-10-12 23:32:35 +00002263 // If we suppressed any diagnostics while performing template argument
2264 // deduction, and if we haven't already instantiated this declaration,
2265 // keep track of these diagnostics. They'll be emitted if this specialization
2266 // is actually used.
2267 if (Info.diag_begin() != Info.diag_end()) {
2268 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2269 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2270 if (Pos == SuppressedDiagnostics.end())
2271 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2272 .append(Info.diag_begin(), Info.diag_end());
2273 }
2274
Mike Stump1eb44332009-09-09 15:08:12 +00002275 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002276}
2277
John McCall9c72c602010-08-27 09:08:28 +00002278/// Gets the type of a function for template-argument-deducton
2279/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002280static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002281 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002282 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002284 if (Method->isInstance()) {
2285 // An instance method that's referenced in a form that doesn't
2286 // look like a member pointer is just invalid.
2287 if (!R.HasFormOfMemberPointer) return QualType();
2288
John McCalleff92132010-02-02 02:21:27 +00002289 return Context.getMemberPointerType(Fn->getType(),
2290 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002291 }
2292
2293 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002294 return Context.getPointerType(Fn->getType());
2295}
2296
2297/// Apply the deduction rules for overload sets.
2298///
2299/// \return the null type if this argument should be treated as an
2300/// undeduced context
2301static QualType
2302ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002303 Expr *Arg, QualType ParamType,
2304 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002305
2306 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002307
John McCall9c72c602010-08-27 09:08:28 +00002308 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002309
Douglas Gregor75f21af2010-08-30 21:04:23 +00002310 // C++0x [temp.deduct.call]p4
2311 unsigned TDF = 0;
2312 if (ParamWasReference)
2313 TDF |= TDF_ParamWithReferenceType;
2314 if (R.IsAddressOfOperand)
2315 TDF |= TDF_IgnoreQualifiers;
2316
John McCalleff92132010-02-02 02:21:27 +00002317 // If there were explicit template arguments, we can only find
2318 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2319 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002320 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002321 // But we can still look for an explicit specialization.
2322 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002323 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002324 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002325 return QualType();
2326 }
2327
2328 // C++0x [temp.deduct.call]p6:
2329 // When P is a function type, pointer to function type, or pointer
2330 // to member function type:
2331
2332 if (!ParamType->isFunctionType() &&
2333 !ParamType->isFunctionPointerType() &&
2334 !ParamType->isMemberFunctionPointerType())
2335 return QualType();
2336
2337 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002338 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2339 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002340 NamedDecl *D = (*I)->getUnderlyingDecl();
2341
2342 // - If the argument is an overload set containing one or more
2343 // function templates, the parameter is treated as a
2344 // non-deduced context.
2345 if (isa<FunctionTemplateDecl>(D))
2346 return QualType();
2347
2348 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002349 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2350 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002351
Douglas Gregor75f21af2010-08-30 21:04:23 +00002352 // Function-to-pointer conversion.
2353 if (!ParamWasReference && ParamType->isPointerType() &&
2354 ArgType->isFunctionType())
2355 ArgType = S.Context.getPointerType(ArgType);
2356
John McCalleff92132010-02-02 02:21:27 +00002357 // - If the argument is an overload set (not containing function
2358 // templates), trial argument deduction is attempted using each
2359 // of the members of the set. If deduction succeeds for only one
2360 // of the overload set members, that member is used as the
2361 // argument value for the deduction. If deduction succeeds for
2362 // more than one member of the overload set the parameter is
2363 // treated as a non-deduced context.
2364
2365 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2366 // Type deduction is done independently for each P/A pair, and
2367 // the deduced template argument values are then combined.
2368 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002369 llvm::SmallVector<DeducedTemplateArgument, 8>
2370 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002371 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002372 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002373 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002374 ParamType, ArgType,
2375 Info, Deduced, TDF);
2376 if (Result) continue;
2377 if (!Match.isNull()) return QualType();
2378 Match = ArgType;
2379 }
2380
2381 return Match;
2382}
2383
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002384/// \brief Perform the adjustments to the parameter and argument types
2385/// described in C++ [temp.deduct.call].
2386///
2387/// \returns true if the caller should not attempt to perform any template
2388/// argument deduction based on this P/A pair.
2389static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2390 TemplateParameterList *TemplateParams,
2391 QualType &ParamType,
2392 QualType &ArgType,
2393 Expr *Arg,
2394 unsigned &TDF) {
2395 // C++0x [temp.deduct.call]p3:
2396 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2397 // are ignored for type deduction.
2398 if (ParamType.getCVRQualifiers())
2399 ParamType = ParamType.getLocalUnqualifiedType();
2400 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2401 if (ParamRefType) {
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002402 // [C++0x] If P is an rvalue reference to a cv-unqualified
2403 // template parameter and the argument is an lvalue, the type
2404 // "lvalue reference to A" is used in place of A for type
2405 // deduction.
2406 if (const RValueReferenceType *RValueRef
2407 = dyn_cast<RValueReferenceType>(ParamType)) {
2408 if (!RValueRef->getPointeeType().getQualifiers() &&
2409 isa<TemplateTypeParmType>(RValueRef->getPointeeType()) &&
2410 Arg->Classify(S.Context).isLValue())
2411 ArgType = S.Context.getLValueReferenceType(ArgType);
2412 }
2413
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002414 // [...] If P is a reference type, the type referred to by P is used
2415 // for type deduction.
2416 ParamType = ParamRefType->getPointeeType();
2417 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002418
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002419 // Overload sets usually make this parameter an undeduced
2420 // context, but there are sometimes special circumstances.
2421 if (ArgType == S.Context.OverloadTy) {
2422 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2423 Arg, ParamType,
2424 ParamRefType != 0);
2425 if (ArgType.isNull())
2426 return true;
2427 }
2428
2429 if (ParamRefType) {
2430 // C++0x [temp.deduct.call]p3:
2431 // [...] If P is of the form T&&, where T is a template parameter, and
2432 // the argument is an lvalue, the type A& is used in place of A for
2433 // type deduction.
2434 if (ParamRefType->isRValueReferenceType() &&
2435 ParamRefType->getAs<TemplateTypeParmType>() &&
2436 Arg->isLValue())
2437 ArgType = S.Context.getLValueReferenceType(ArgType);
2438 } else {
2439 // C++ [temp.deduct.call]p2:
2440 // If P is not a reference type:
2441 // - If A is an array type, the pointer type produced by the
2442 // array-to-pointer standard conversion (4.2) is used in place of
2443 // A for type deduction; otherwise,
2444 if (ArgType->isArrayType())
2445 ArgType = S.Context.getArrayDecayedType(ArgType);
2446 // - If A is a function type, the pointer type produced by the
2447 // function-to-pointer standard conversion (4.3) is used in place
2448 // of A for type deduction; otherwise,
2449 else if (ArgType->isFunctionType())
2450 ArgType = S.Context.getPointerType(ArgType);
2451 else {
2452 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2453 // type are ignored for type deduction.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002454 if (ArgType.getCVRQualifiers())
2455 ArgType = ArgType.getUnqualifiedType();
2456 }
2457 }
2458
2459 // C++0x [temp.deduct.call]p4:
2460 // In general, the deduction process attempts to find template argument
2461 // values that will make the deduced A identical to A (after the type A
2462 // is transformed as described above). [...]
2463 TDF = TDF_SkipNonDependent;
2464
2465 // - If the original P is a reference type, the deduced A (i.e., the
2466 // type referred to by the reference) can be more cv-qualified than
2467 // the transformed A.
2468 if (ParamRefType)
2469 TDF |= TDF_ParamWithReferenceType;
2470 // - The transformed A can be another pointer or pointer to member
2471 // type that can be converted to the deduced A via a qualification
2472 // conversion (4.4).
2473 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2474 ArgType->isObjCObjectPointerType())
2475 TDF |= TDF_IgnoreQualifiers;
2476 // - If P is a class and P has the form simple-template-id, then the
2477 // transformed A can be a derived class of the deduced A. Likewise,
2478 // if P is a pointer to a class of the form simple-template-id, the
2479 // transformed A can be a pointer to a derived class pointed to by
2480 // the deduced A.
2481 if (isSimpleTemplateIdType(ParamType) ||
2482 (isa<PointerType>(ParamType) &&
2483 isSimpleTemplateIdType(
2484 ParamType->getAs<PointerType>()->getPointeeType())))
2485 TDF |= TDF_DerivedClass;
2486
2487 return false;
2488}
2489
Douglas Gregore53060f2009-06-25 22:08:12 +00002490/// \brief Perform template argument deduction from a function call
2491/// (C++ [temp.deduct.call]).
2492///
2493/// \param FunctionTemplate the function template for which we are performing
2494/// template argument deduction.
2495///
Douglas Gregor48026d22010-01-11 18:40:55 +00002496/// \param ExplicitTemplateArguments the explicit template arguments provided
2497/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002498///
Douglas Gregore53060f2009-06-25 22:08:12 +00002499/// \param Args the function call arguments
2500///
2501/// \param NumArgs the number of arguments in Args
2502///
Douglas Gregor48026d22010-01-11 18:40:55 +00002503/// \param Name the name of the function being called. This is only significant
2504/// when the function template is a conversion function template, in which
2505/// case this routine will also perform template argument deduction based on
2506/// the function to which
2507///
Douglas Gregore53060f2009-06-25 22:08:12 +00002508/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002509/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002510/// template argument deduction.
2511///
2512/// \param Info the argument will be updated to provide additional information
2513/// about template argument deduction.
2514///
2515/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002516Sema::TemplateDeductionResult
2517Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002518 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002519 Expr **Args, unsigned NumArgs,
2520 FunctionDecl *&Specialization,
2521 TemplateDeductionInfo &Info) {
2522 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002523
Douglas Gregore53060f2009-06-25 22:08:12 +00002524 // C++ [temp.deduct.call]p1:
2525 // Template argument deduction is done by comparing each function template
2526 // parameter type (call it P) with the type of the corresponding argument
2527 // of the call (call it A) as described below.
2528 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002529 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002530 return TDK_TooFewArguments;
2531 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002532 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002533 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002534 if (Proto->isTemplateVariadic())
2535 /* Do nothing */;
2536 else if (Proto->isVariadic())
2537 CheckArgs = Function->getNumParams();
2538 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002539 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002540 }
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002542 // The types of the parameters from which we will perform template argument
2543 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002544 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002545 TemplateParameterList *TemplateParams
2546 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002547 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002548 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002549 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002550 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002551 TemplateDeductionResult Result =
2552 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002553 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002554 Deduced,
2555 ParamTypes,
2556 0,
2557 Info);
2558 if (Result)
2559 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002560
2561 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002562 } else {
2563 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002564 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002565 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2566 }
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002568 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002569 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002570 unsigned ArgIdx = 0;
2571 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2572 ParamIdx != NumParams; ++ParamIdx) {
2573 QualType ParamType = ParamTypes[ParamIdx];
2574
2575 const PackExpansionType *ParamExpansion
2576 = dyn_cast<PackExpansionType>(ParamType);
2577 if (!ParamExpansion) {
2578 // Simple case: matching a function parameter to a function argument.
2579 if (ArgIdx >= CheckArgs)
2580 break;
2581
2582 Expr *Arg = Args[ArgIdx++];
2583 QualType ArgType = Arg->getType();
2584 unsigned TDF = 0;
2585 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2586 ParamType, ArgType, Arg,
2587 TDF))
2588 continue;
2589
2590 if (TemplateDeductionResult Result
2591 = ::DeduceTemplateArguments(*this, TemplateParams,
2592 ParamType, ArgType, Info, Deduced,
2593 TDF))
2594 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002596 // FIXME: we need to check that the deduced A is the same as A,
2597 // modulo the various allowed differences.
2598 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002599 }
2600
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002601 // C++0x [temp.deduct.call]p1:
2602 // For a function parameter pack that occurs at the end of the
2603 // parameter-declaration-list, the type A of each remaining argument of
2604 // the call is compared with the type P of the declarator-id of the
2605 // function parameter pack. Each comparison deduces template arguments
2606 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002607 // the function parameter pack. For a function parameter pack that does
2608 // not occur at the end of the parameter-declaration-list, the type of
2609 // the parameter pack is a non-deduced context.
2610 if (ParamIdx + 1 < NumParams)
2611 break;
2612
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002613 QualType ParamPattern = ParamExpansion->getPattern();
2614 llvm::SmallVector<unsigned, 2> PackIndices;
2615 {
2616 llvm::BitVector SawIndices(TemplateParams->size());
2617 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2618 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2619 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2620 unsigned Depth, Index;
2621 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2622 if (Depth == 0 && !SawIndices[Index]) {
2623 SawIndices[Index] = true;
2624 PackIndices.push_back(Index);
2625 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002626 }
2627 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002628 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2629
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002630 // Keep track of the deduced template arguments for each parameter pack
2631 // expanded by this pack expansion (the outer index) and for each
2632 // template argument (the inner SmallVectors).
2633 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002634 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002635 llvm::SmallVector<DeducedTemplateArgument, 2>
2636 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002637 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2638 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002639 bool HasAnyArguments = false;
2640 for (; ArgIdx < NumArgs; ++ArgIdx) {
2641 HasAnyArguments = true;
2642
2643 ParamType = ParamPattern;
2644 Expr *Arg = Args[ArgIdx];
2645 QualType ArgType = Arg->getType();
2646 unsigned TDF = 0;
2647 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2648 ParamType, ArgType, Arg,
2649 TDF)) {
2650 // We can't actually perform any deduction for this argument, so stop
2651 // deduction at this point.
2652 ++ArgIdx;
2653 break;
2654 }
2655
2656 if (TemplateDeductionResult Result
2657 = ::DeduceTemplateArguments(*this, TemplateParams,
2658 ParamType, ArgType, Info, Deduced,
2659 TDF))
2660 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002662 // Capture the deduced template arguments for each parameter pack expanded
2663 // by this pack expansion, add them to the list of arguments we've deduced
2664 // for that pack, then clear out the deduced argument.
2665 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2666 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2667 if (!DeducedArg.isNull()) {
2668 NewlyDeducedPacks[I].push_back(DeducedArg);
2669 DeducedArg = DeducedTemplateArgument();
2670 }
2671 }
2672 }
2673
2674 // Build argument packs for each of the parameter packs expanded by this
2675 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002676 if (Sema::TemplateDeductionResult Result
2677 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2678 Deduced, PackIndices, SavedPacks,
2679 NewlyDeducedPacks, Info))
2680 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002682 // After we've matching against a parameter pack, we're done.
2683 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002684 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002685
Mike Stump1eb44332009-09-09 15:08:12 +00002686 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002687 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002688 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002689}
2690
Douglas Gregor83314aa2009-07-08 20:55:45 +00002691/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002692/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2693/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002694///
2695/// \param FunctionTemplate the function template for which we are performing
2696/// template argument deduction.
2697///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002698/// \param ExplicitTemplateArguments the explicitly-specified template
2699/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002700///
2701/// \param ArgFunctionType the function type that will be used as the
2702/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002703/// function template's function type. This type may be NULL, if there is no
2704/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002705///
2706/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002707/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002708/// template argument deduction.
2709///
2710/// \param Info the argument will be updated to provide additional information
2711/// about template argument deduction.
2712///
2713/// \returns the result of template argument deduction.
2714Sema::TemplateDeductionResult
2715Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002716 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002717 QualType ArgFunctionType,
2718 FunctionDecl *&Specialization,
2719 TemplateDeductionInfo &Info) {
2720 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2721 TemplateParameterList *TemplateParams
2722 = FunctionTemplate->getTemplateParameters();
2723 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregor83314aa2009-07-08 20:55:45 +00002725 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002726 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002727 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2728 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002729 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002730 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002731 if (TemplateDeductionResult Result
2732 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002733 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002734 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002735 &FunctionType, Info))
2736 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002737
2738 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002739 }
2740
2741 // Template argument deduction for function templates in a SFINAE context.
2742 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002743 SFINAETrap Trap(*this);
2744
John McCalleff92132010-02-02 02:21:27 +00002745 Deduced.resize(TemplateParams->size());
2746
Douglas Gregor4b52e252009-12-21 23:17:24 +00002747 if (!ArgFunctionType.isNull()) {
2748 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002749 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002750 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002751 FunctionType, ArgFunctionType, Info,
2752 Deduced, 0))
2753 return Result;
2754 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002755
2756 if (TemplateDeductionResult Result
2757 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2758 NumExplicitlySpecified,
2759 Specialization, Info))
2760 return Result;
2761
2762 // If the requested function type does not match the actual type of the
2763 // specialization, template argument deduction fails.
2764 if (!ArgFunctionType.isNull() &&
2765 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2766 return TDK_NonDeducedMismatch;
2767
2768 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002769}
2770
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002771/// \brief Deduce template arguments for a templated conversion
2772/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2773/// conversion function template specialization.
2774Sema::TemplateDeductionResult
2775Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2776 QualType ToType,
2777 CXXConversionDecl *&Specialization,
2778 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002779 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002780 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2781 QualType FromType = Conv->getConversionType();
2782
2783 // Canonicalize the types for deduction.
2784 QualType P = Context.getCanonicalType(FromType);
2785 QualType A = Context.getCanonicalType(ToType);
2786
2787 // C++0x [temp.deduct.conv]p3:
2788 // If P is a reference type, the type referred to by P is used for
2789 // type deduction.
2790 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2791 P = PRef->getPointeeType();
2792
2793 // C++0x [temp.deduct.conv]p3:
2794 // If A is a reference type, the type referred to by A is used
2795 // for type deduction.
2796 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2797 A = ARef->getPointeeType();
2798 // C++ [temp.deduct.conv]p2:
2799 //
Mike Stump1eb44332009-09-09 15:08:12 +00002800 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002801 else {
2802 assert(!A->isReferenceType() && "Reference types were handled above");
2803
2804 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002805 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002806 // of P for type deduction; otherwise,
2807 if (P->isArrayType())
2808 P = Context.getArrayDecayedType(P);
2809 // - If P is a function type, the pointer type produced by the
2810 // function-to-pointer standard conversion (4.3) is used in
2811 // place of P for type deduction; otherwise,
2812 else if (P->isFunctionType())
2813 P = Context.getPointerType(P);
2814 // - If P is a cv-qualified type, the top level cv-qualifiers of
2815 // P’s type are ignored for type deduction.
2816 else
2817 P = P.getUnqualifiedType();
2818
2819 // C++0x [temp.deduct.conv]p3:
2820 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2821 // type are ignored for type deduction.
2822 A = A.getUnqualifiedType();
2823 }
2824
2825 // Template argument deduction for function templates in a SFINAE context.
2826 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002827 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002828
2829 // C++ [temp.deduct.conv]p1:
2830 // Template argument deduction is done by comparing the return
2831 // type of the template conversion function (call it P) with the
2832 // type that is required as the result of the conversion (call it
2833 // A) as described in 14.8.2.4.
2834 TemplateParameterList *TemplateParams
2835 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002836 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002837 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002838
2839 // C++0x [temp.deduct.conv]p4:
2840 // In general, the deduction process attempts to find template
2841 // argument values that will make the deduced A identical to
2842 // A. However, there are two cases that allow a difference:
2843 unsigned TDF = 0;
2844 // - If the original A is a reference type, A can be more
2845 // cv-qualified than the deduced A (i.e., the type referred to
2846 // by the reference)
2847 if (ToType->isReferenceType())
2848 TDF |= TDF_ParamWithReferenceType;
2849 // - The deduced A can be another pointer or pointer to member
2850 // type that can be converted to A via a qualification
2851 // conversion.
2852 //
2853 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2854 // both P and A are pointers or member pointers. In this case, we
2855 // just ignore cv-qualifiers completely).
2856 if ((P->isPointerType() && A->isPointerType()) ||
2857 (P->isMemberPointerType() && P->isMemberPointerType()))
2858 TDF |= TDF_IgnoreQualifiers;
2859 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002860 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002861 P, A, Info, Deduced, TDF))
2862 return Result;
2863
2864 // FIXME: we need to check that the deduced A is the same as A,
2865 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002867 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002868 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002869 FunctionDecl *Spec = 0;
2870 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002871 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2872 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002873 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2874 return Result;
2875}
2876
Douglas Gregor4b52e252009-12-21 23:17:24 +00002877/// \brief Deduce template arguments for a function template when there is
2878/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2879///
2880/// \param FunctionTemplate the function template for which we are performing
2881/// template argument deduction.
2882///
2883/// \param ExplicitTemplateArguments the explicitly-specified template
2884/// arguments.
2885///
2886/// \param Specialization if template argument deduction was successful,
2887/// this will be set to the function template specialization produced by
2888/// template argument deduction.
2889///
2890/// \param Info the argument will be updated to provide additional information
2891/// about template argument deduction.
2892///
2893/// \returns the result of template argument deduction.
2894Sema::TemplateDeductionResult
2895Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2896 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2897 FunctionDecl *&Specialization,
2898 TemplateDeductionInfo &Info) {
2899 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2900 QualType(), Specialization, Info);
2901}
2902
Douglas Gregor8a514912009-09-14 18:39:43 +00002903static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002904MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2905 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002906 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002907 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002908
2909/// \brief If this is a non-static member function,
2910static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2911 CXXMethodDecl *Method,
2912 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2913 if (Method->isStatic())
2914 return;
2915
2916 // C++ [over.match.funcs]p4:
2917 //
2918 // For non-static member functions, the type of the implicit
2919 // object parameter is
2920 // — "lvalue reference to cv X" for functions declared without a
2921 // ref-qualifier or with the & ref-qualifier
2922 // - "rvalue reference to cv X" for functions declared with the
2923 // && ref-qualifier
2924 //
2925 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2926 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2927 ArgTy = Context.getQualifiedType(ArgTy,
2928 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2929 ArgTy = Context.getLValueReferenceType(ArgTy);
2930 ArgTypes.push_back(ArgTy);
2931}
2932
Douglas Gregor8a514912009-09-14 18:39:43 +00002933/// \brief Determine whether the function template \p FT1 is at least as
2934/// specialized as \p FT2.
2935static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002936 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002937 FunctionTemplateDecl *FT1,
2938 FunctionTemplateDecl *FT2,
2939 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002940 unsigned NumCallArguments,
Douglas Gregor8a514912009-09-14 18:39:43 +00002941 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2942 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2943 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2944 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2945 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2946
2947 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2948 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002949 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002950 Deduced.resize(TemplateParams->size());
2951
2952 // C++0x [temp.deduct.partial]p3:
2953 // The types used to determine the ordering depend on the context in which
2954 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002955 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002956 CXXMethodDecl *Method1 = 0;
2957 CXXMethodDecl *Method2 = 0;
2958 bool IsNonStatic2 = false;
2959 bool IsNonStatic1 = false;
2960 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002961 switch (TPOC) {
2962 case TPOC_Call: {
2963 // - In the context of a function call, the function parameter types are
2964 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002965 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2966 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2967 IsNonStatic1 = Method1 && !Method1->isStatic();
2968 IsNonStatic2 = Method2 && !Method2->isStatic();
2969
2970 // C++0x [temp.func.order]p3:
2971 // [...] If only one of the function templates is a non-static
2972 // member, that function template is considered to have a new
2973 // first parameter inserted in its function parameter list. The
2974 // new parameter is of type "reference to cv A," where cv are
2975 // the cv-qualifiers of the function template (if any) and A is
2976 // the class of which the function template is a member.
2977 //
2978 // C++98/03 doesn't have this provision, so instead we drop the
2979 // first argument of the free function or static member, which
2980 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002981 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002982 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2983 IsNonStatic2 && !IsNonStatic1;
2984 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002985 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002986 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002987 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002988
2989 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002990 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2991 IsNonStatic1 && !IsNonStatic2;
2992 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002993 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2994 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002995 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002996
2997 // C++ [temp.func.order]p5:
2998 // The presence of unused ellipsis and default arguments has no effect on
2999 // the partial ordering of function templates.
3000 if (Args1.size() > NumCallArguments)
3001 Args1.resize(NumCallArguments);
3002 if (Args2.size() > NumCallArguments)
3003 Args2.resize(NumCallArguments);
3004 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3005 Args1.data(), Args1.size(), Info, Deduced,
3006 TDF_None, /*PartialOrdering=*/true,
3007 QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003008 return false;
3009
3010 break;
3011 }
3012
3013 case TPOC_Conversion:
3014 // - In the context of a call to a conversion operator, the return types
3015 // of the conversion function templates are used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003016 if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
3017 Proto1->getResultType(), Info, Deduced,
3018 TDF_None, /*PartialOrdering=*/true,
3019 QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003020 return false;
3021 break;
3022
3023 case TPOC_Other:
3024 // - In other contexts (14.6.6.2) the function template’s function type
3025 // is used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003026 // FIXME: Don't we actually want to perform the adjustments on the parameter
3027 // types?
3028 if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
3029 FD1->getType(), Info, Deduced, TDF_None,
3030 /*PartialOrdering=*/true, QualifierComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003031 return false;
3032 break;
3033 }
3034
3035 // C++0x [temp.deduct.partial]p11:
3036 // In most cases, all template parameters must have values in order for
3037 // deduction to succeed, but for partial ordering purposes a template
3038 // parameter may remain without a value provided it is not used in the
3039 // types being used for partial ordering. [ Note: a template parameter used
3040 // in a non-deduced context is considered used. -end note]
3041 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3042 for (; ArgIdx != NumArgs; ++ArgIdx)
3043 if (Deduced[ArgIdx].isNull())
3044 break;
3045
3046 if (ArgIdx == NumArgs) {
3047 // All template arguments were deduced. FT1 is at least as specialized
3048 // as FT2.
3049 return true;
3050 }
3051
Douglas Gregore73bb602009-09-14 21:25:05 +00003052 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003053 llvm::SmallVector<bool, 4> UsedParameters;
3054 UsedParameters.resize(TemplateParams->size());
3055 switch (TPOC) {
3056 case TPOC_Call: {
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003057 unsigned NumParams = std::min(NumCallArguments,
3058 std::min(Proto1->getNumArgs(),
3059 Proto2->getNumArgs()));
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003060 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3061 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3062 TemplateParams->getDepth(), UsedParameters);
3063 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003064 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3065 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003066 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003067 break;
3068 }
3069
3070 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003071 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3072 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003073 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003074 break;
3075
3076 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003077 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3078 TemplateParams->getDepth(),
3079 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003080 break;
3081 }
3082
3083 for (; ArgIdx != NumArgs; ++ArgIdx)
3084 // If this argument had no value deduced but was used in one of the types
3085 // used for partial ordering, then deduction fails.
3086 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3087 return false;
3088
3089 return true;
3090}
3091
Douglas Gregor9da95e62011-01-16 16:03:23 +00003092/// \brief Determine whether this a function template whose parameter-type-list
3093/// ends with a function parameter pack.
3094static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3095 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3096 unsigned NumParams = Function->getNumParams();
3097 if (NumParams == 0)
3098 return false;
3099
3100 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3101 if (!Last->isParameterPack())
3102 return false;
3103
3104 // Make sure that no previous parameter is a parameter pack.
3105 while (--NumParams > 0) {
3106 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3107 return false;
3108 }
3109
3110 return true;
3111}
Douglas Gregor8a514912009-09-14 18:39:43 +00003112
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003113/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003114/// to the rules of function template partial ordering (C++ [temp.func.order]).
3115///
3116/// \param FT1 the first function template
3117///
3118/// \param FT2 the second function template
3119///
Douglas Gregor8a514912009-09-14 18:39:43 +00003120/// \param TPOC the context in which we are performing partial ordering of
3121/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003122///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003123/// \param NumCallArguments The number of arguments in a call, used only
3124/// when \c TPOC is \c TPOC_Call.
3125///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003126/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003127/// template is more specialized, returns NULL.
3128FunctionTemplateDecl *
3129Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3130 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003131 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003132 TemplatePartialOrderingContext TPOC,
3133 unsigned NumCallArguments) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003134 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003135 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3136 NumCallArguments, 0);
John McCall5769d612010-02-08 23:07:23 +00003137 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003138 NumCallArguments,
Douglas Gregor8a514912009-09-14 18:39:43 +00003139 &QualifierComparisons);
3140
3141 if (Better1 != Better2) // We have a clear winner
3142 return Better1? FT1 : FT2;
3143
3144 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003145 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003146
3147
3148 // C++0x [temp.deduct.partial]p10:
3149 // If for each type being considered a given template is at least as
3150 // specialized for all types and more specialized for some set of types and
3151 // the other template is not more specialized for any types or is not at
3152 // least as specialized for any types, then the given template is more
3153 // specialized than the other template. Otherwise, neither template is more
3154 // specialized than the other.
3155 Better1 = false;
3156 Better2 = false;
3157 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3158 // C++0x [temp.deduct.partial]p9:
3159 // If, for a given type, deduction succeeds in both directions (i.e., the
3160 // types are identical after the transformations above) and if the type
3161 // from the argument template is more cv-qualified than the type from the
3162 // parameter template (as described above) that type is considered to be
3163 // more specialized than the other. If neither type is more cv-qualified
3164 // than the other then neither type is more specialized than the other.
3165 switch (QualifierComparisons[I]) {
3166 case NeitherMoreQualified:
3167 break;
3168
3169 case ParamMoreQualified:
3170 Better1 = true;
3171 if (Better2)
3172 return 0;
3173 break;
3174
3175 case ArgMoreQualified:
3176 Better2 = true;
3177 if (Better1)
3178 return 0;
3179 break;
3180 }
3181 }
3182
3183 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003184 if (Better1)
3185 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003186 else if (Better2)
3187 return FT2;
Douglas Gregor9da95e62011-01-16 16:03:23 +00003188
3189 // FIXME: This mimics what GCC implements, but doesn't match up with the
3190 // proposed resolution for core issue 692. This area needs to be sorted out,
3191 // but for now we attempt to maintain compatibility.
3192 bool Variadic1 = isVariadicFunctionTemplate(FT1);
3193 bool Variadic2 = isVariadicFunctionTemplate(FT2);
3194 if (Variadic1 != Variadic2)
3195 return Variadic1? FT2 : FT1;
3196
3197 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003198}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003199
Douglas Gregord5a423b2009-09-25 18:43:00 +00003200/// \brief Determine if the two templates are equivalent.
3201static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3202 if (T1 == T2)
3203 return true;
3204
3205 if (!T1 || !T2)
3206 return false;
3207
3208 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3209}
3210
3211/// \brief Retrieve the most specialized of the given function template
3212/// specializations.
3213///
John McCallc373d482010-01-27 01:50:18 +00003214/// \param SpecBegin the start iterator of the function template
3215/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003216///
John McCallc373d482010-01-27 01:50:18 +00003217/// \param SpecEnd the end iterator of the function template
3218/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003219///
3220/// \param TPOC the partial ordering context to use to compare the function
3221/// template specializations.
3222///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003223/// \param NumCallArguments The number of arguments in a call, used only
3224/// when \c TPOC is \c TPOC_Call.
3225///
Douglas Gregord5a423b2009-09-25 18:43:00 +00003226/// \param Loc the location where the ambiguity or no-specializations
3227/// diagnostic should occur.
3228///
3229/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3230/// no matching candidates.
3231///
3232/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3233/// occurs.
3234///
3235/// \param CandidateDiag partial diagnostic used for each function template
3236/// specialization that is a candidate in the ambiguous ordering. One parameter
3237/// in this diagnostic should be unbound, which will correspond to the string
3238/// describing the template arguments for the function template specialization.
3239///
3240/// \param Index if non-NULL and the result of this function is non-nULL,
3241/// receives the index corresponding to the resulting function template
3242/// specialization.
3243///
3244/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003245/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003246///
3247/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3248/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003249UnresolvedSetIterator
3250Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003251 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00003252 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003253 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00003254 SourceLocation Loc,
3255 const PartialDiagnostic &NoneDiag,
3256 const PartialDiagnostic &AmbigDiag,
3257 const PartialDiagnostic &CandidateDiag) {
3258 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003259 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003260 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003261 }
3262
John McCallc373d482010-01-27 01:50:18 +00003263 if (SpecBegin + 1 == SpecEnd)
3264 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003265
3266 // Find the function template that is better than all of the templates it
3267 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003268 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003269 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003270 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003271 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003272 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3273 FunctionTemplateDecl *Challenger
3274 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003275 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003276 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003277 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003278 Challenger)) {
3279 Best = I;
3280 BestTemplate = Challenger;
3281 }
3282 }
3283
3284 // Make sure that the "best" function template is more specialized than all
3285 // of the others.
3286 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003287 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3288 FunctionTemplateDecl *Challenger
3289 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003290 if (I != Best &&
3291 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003292 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003293 BestTemplate)) {
3294 Ambiguous = true;
3295 break;
3296 }
3297 }
3298
3299 if (!Ambiguous) {
3300 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003301 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003302 }
3303
3304 // Diagnose the ambiguity.
3305 Diag(Loc, AmbigDiag);
3306
3307 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003308 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3309 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003310 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003311 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3312 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003313
John McCallc373d482010-01-27 01:50:18 +00003314 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003315}
3316
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003317/// \brief Returns the more specialized class template partial specialization
3318/// according to the rules of partial ordering of class template partial
3319/// specializations (C++ [temp.class.order]).
3320///
3321/// \param PS1 the first class template partial specialization
3322///
3323/// \param PS2 the second class template partial specialization
3324///
3325/// \returns the more specialized class template partial specialization. If
3326/// neither partial specialization is more specialized, returns NULL.
3327ClassTemplatePartialSpecializationDecl *
3328Sema::getMoreSpecializedPartialSpecialization(
3329 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003330 ClassTemplatePartialSpecializationDecl *PS2,
3331 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003332 // C++ [temp.class.order]p1:
3333 // For two class template partial specializations, the first is at least as
3334 // specialized as the second if, given the following rewrite to two
3335 // function templates, the first function template is at least as
3336 // specialized as the second according to the ordering rules for function
3337 // templates (14.6.6.2):
3338 // - the first function template has the same template parameters as the
3339 // first partial specialization and has a single function parameter
3340 // whose type is a class template specialization with the template
3341 // arguments of the first partial specialization, and
3342 // - the second function template has the same template parameters as the
3343 // second partial specialization and has a single function parameter
3344 // whose type is a class template specialization with the template
3345 // arguments of the second partial specialization.
3346 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003347 // Rather than synthesize function templates, we merely perform the
3348 // equivalent partial ordering by performing deduction directly on
3349 // the template arguments of the class template partial
3350 // specializations. This computation is slightly simpler than the
3351 // general problem of function template partial ordering, because
3352 // class template partial specializations are more constrained. We
3353 // know that every template parameter is deducible from the class
3354 // template partial specialization's template arguments, for
3355 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003356 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003357 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003358
3359 QualType PT1 = PS1->getInjectedSpecializationType();
3360 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003361
3362 // Determine whether PS1 is at least as specialized as PS2
3363 Deduced.resize(PS2->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003364 bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3365 PT2, PT1, Info, Deduced, TDF_None,
3366 /*PartialOrdering=*/true,
3367 /*QualifierComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003368 if (Better1) {
3369 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3370 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003371 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3372 PS1->getTemplateArgs(),
3373 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003374 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003375
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003376 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003377 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003378 Deduced.resize(PS1->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003379 bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3380 PT1, PT2, Info, Deduced, TDF_None,
3381 /*PartialOrdering=*/true,
3382 /*QualifierComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003383 if (Better2) {
3384 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3385 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003386 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3387 PS2->getTemplateArgs(),
3388 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003389 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003390
3391 if (Better1 == Better2)
3392 return 0;
3393
3394 return Better1? PS1 : PS2;
3395}
3396
Mike Stump1eb44332009-09-09 15:08:12 +00003397static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003398MarkUsedTemplateParameters(Sema &SemaRef,
3399 const TemplateArgument &TemplateArg,
3400 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003401 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003402 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003403
Douglas Gregore73bb602009-09-14 21:25:05 +00003404/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003405/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003406static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003407MarkUsedTemplateParameters(Sema &SemaRef,
3408 const Expr *E,
3409 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003410 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003411 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003412 // We can deduce from a pack expansion.
3413 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3414 E = Expansion->getPattern();
3415
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003416 // Skip through any implicit casts we added while type-checking.
3417 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3418 E = ICE->getSubExpr();
3419
Douglas Gregore73bb602009-09-14 21:25:05 +00003420 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3421 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003422 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003423 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003424 return;
3425
Mike Stump1eb44332009-09-09 15:08:12 +00003426 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003427 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3428 if (!NTTP)
3429 return;
3430
Douglas Gregored9c0f92009-10-29 00:04:11 +00003431 if (NTTP->getDepth() == Depth)
3432 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003433}
3434
Douglas Gregore73bb602009-09-14 21:25:05 +00003435/// \brief Mark the template parameters that are used by the given
3436/// nested name specifier.
3437static void
3438MarkUsedTemplateParameters(Sema &SemaRef,
3439 NestedNameSpecifier *NNS,
3440 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003441 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003442 llvm::SmallVectorImpl<bool> &Used) {
3443 if (!NNS)
3444 return;
3445
Douglas Gregored9c0f92009-10-29 00:04:11 +00003446 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3447 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003448 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003449 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003450}
3451
3452/// \brief Mark the template parameters that are used by the given
3453/// template name.
3454static void
3455MarkUsedTemplateParameters(Sema &SemaRef,
3456 TemplateName Name,
3457 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003458 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003459 llvm::SmallVectorImpl<bool> &Used) {
3460 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3461 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003462 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3463 if (TTP->getDepth() == Depth)
3464 Used[TTP->getIndex()] = true;
3465 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003466 return;
3467 }
3468
Douglas Gregor788cd062009-11-11 01:00:40 +00003469 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3470 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3471 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003472 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003473 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3474 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003475}
3476
3477/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003478/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003479static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003480MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3481 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003482 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003483 llvm::SmallVectorImpl<bool> &Used) {
3484 if (T.isNull())
3485 return;
3486
Douglas Gregor031a5882009-06-13 00:26:55 +00003487 // Non-dependent types have nothing deducible
3488 if (!T->isDependentType())
3489 return;
3490
3491 T = SemaRef.Context.getCanonicalType(T);
3492 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003493 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003494 MarkUsedTemplateParameters(SemaRef,
3495 cast<PointerType>(T)->getPointeeType(),
3496 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003497 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003498 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003499 break;
3500
3501 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003502 MarkUsedTemplateParameters(SemaRef,
3503 cast<BlockPointerType>(T)->getPointeeType(),
3504 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003505 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003506 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003507 break;
3508
3509 case Type::LValueReference:
3510 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003511 MarkUsedTemplateParameters(SemaRef,
3512 cast<ReferenceType>(T)->getPointeeType(),
3513 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003514 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003515 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003516 break;
3517
3518 case Type::MemberPointer: {
3519 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003520 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003521 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003522 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003523 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003524 break;
3525 }
3526
3527 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003528 MarkUsedTemplateParameters(SemaRef,
3529 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003530 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003531 // Fall through to check the element type
3532
3533 case Type::ConstantArray:
3534 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003535 MarkUsedTemplateParameters(SemaRef,
3536 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003537 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003538 break;
3539
3540 case Type::Vector:
3541 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003542 MarkUsedTemplateParameters(SemaRef,
3543 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003544 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003545 break;
3546
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003547 case Type::DependentSizedExtVector: {
3548 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003549 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003550 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003551 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003552 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003553 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003554 break;
3555 }
3556
Douglas Gregor031a5882009-06-13 00:26:55 +00003557 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003558 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003559 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003560 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003561 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003562 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003563 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003564 break;
3565 }
3566
Douglas Gregored9c0f92009-10-29 00:04:11 +00003567 case Type::TemplateTypeParm: {
3568 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3569 if (TTP->getDepth() == Depth)
3570 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003571 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003572 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003573
Douglas Gregor0bc15d92011-01-14 05:11:40 +00003574 case Type::SubstTemplateTypeParmPack: {
3575 const SubstTemplateTypeParmPackType *Subst
3576 = cast<SubstTemplateTypeParmPackType>(T);
3577 MarkUsedTemplateParameters(SemaRef,
3578 QualType(Subst->getReplacedParameter(), 0),
3579 OnlyDeduced, Depth, Used);
3580 MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
3581 OnlyDeduced, Depth, Used);
3582 break;
3583 }
3584
John McCall31f17ec2010-04-27 00:57:59 +00003585 case Type::InjectedClassName:
3586 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3587 // fall through
3588
Douglas Gregor031a5882009-06-13 00:26:55 +00003589 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003590 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003591 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003592 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003593 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003594
3595 // C++0x [temp.deduct.type]p9:
3596 // If the template argument list of P contains a pack expansion that is not
3597 // the last template argument, the entire template argument list is a
3598 // non-deduced context.
3599 if (OnlyDeduced &&
3600 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3601 break;
3602
Douglas Gregore73bb602009-09-14 21:25:05 +00003603 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003604 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3605 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003606 break;
3607 }
3608
Douglas Gregore73bb602009-09-14 21:25:05 +00003609 case Type::Complex:
3610 if (!OnlyDeduced)
3611 MarkUsedTemplateParameters(SemaRef,
3612 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003613 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003614 break;
3615
Douglas Gregor4714c122010-03-31 17:34:00 +00003616 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003617 if (!OnlyDeduced)
3618 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003619 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003620 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003621 break;
3622
John McCall33500952010-06-11 00:33:02 +00003623 case Type::DependentTemplateSpecialization: {
3624 const DependentTemplateSpecializationType *Spec
3625 = cast<DependentTemplateSpecializationType>(T);
3626 if (!OnlyDeduced)
3627 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3628 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003629
3630 // C++0x [temp.deduct.type]p9:
3631 // If the template argument list of P contains a pack expansion that is not
3632 // the last template argument, the entire template argument list is a
3633 // non-deduced context.
3634 if (OnlyDeduced &&
3635 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3636 break;
3637
John McCall33500952010-06-11 00:33:02 +00003638 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3639 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3640 Used);
3641 break;
3642 }
3643
John McCallad5e7382010-03-01 23:49:17 +00003644 case Type::TypeOf:
3645 if (!OnlyDeduced)
3646 MarkUsedTemplateParameters(SemaRef,
3647 cast<TypeOfType>(T)->getUnderlyingType(),
3648 OnlyDeduced, Depth, Used);
3649 break;
3650
3651 case Type::TypeOfExpr:
3652 if (!OnlyDeduced)
3653 MarkUsedTemplateParameters(SemaRef,
3654 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3655 OnlyDeduced, Depth, Used);
3656 break;
3657
3658 case Type::Decltype:
3659 if (!OnlyDeduced)
3660 MarkUsedTemplateParameters(SemaRef,
3661 cast<DecltypeType>(T)->getUnderlyingExpr(),
3662 OnlyDeduced, Depth, Used);
3663 break;
3664
Douglas Gregor7536dd52010-12-20 02:24:11 +00003665 case Type::PackExpansion:
3666 MarkUsedTemplateParameters(SemaRef,
3667 cast<PackExpansionType>(T)->getPattern(),
3668 OnlyDeduced, Depth, Used);
3669 break;
3670
Douglas Gregore73bb602009-09-14 21:25:05 +00003671 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003672 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003673 case Type::VariableArray:
3674 case Type::FunctionNoProto:
3675 case Type::Record:
3676 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003677 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003678 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003679 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003680 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003681#define TYPE(Class, Base)
3682#define ABSTRACT_TYPE(Class, Base)
3683#define DEPENDENT_TYPE(Class, Base)
3684#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3685#include "clang/AST/TypeNodes.def"
3686 break;
3687 }
3688}
3689
Douglas Gregore73bb602009-09-14 21:25:05 +00003690/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003691/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003692static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003693MarkUsedTemplateParameters(Sema &SemaRef,
3694 const TemplateArgument &TemplateArg,
3695 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003696 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003697 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003698 switch (TemplateArg.getKind()) {
3699 case TemplateArgument::Null:
3700 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003701 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003702 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregor031a5882009-06-13 00:26:55 +00003704 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003705 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003706 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003707 break;
3708
Douglas Gregor788cd062009-11-11 01:00:40 +00003709 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003710 case TemplateArgument::TemplateExpansion:
3711 MarkUsedTemplateParameters(SemaRef,
3712 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003713 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003714 break;
3715
3716 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003717 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003718 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003719 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003720
Anders Carlssond01b1da2009-06-15 17:04:53 +00003721 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003722 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3723 PEnd = TemplateArg.pack_end();
3724 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003725 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003726 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003727 }
3728}
3729
3730/// \brief Mark the template parameters can be deduced by the given
3731/// template argument list.
3732///
3733/// \param TemplateArgs the template argument list from which template
3734/// parameters will be deduced.
3735///
3736/// \param Deduced a bit vector whose elements will be set to \c true
3737/// to indicate when the corresponding template parameter will be
3738/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003739void
Douglas Gregore73bb602009-09-14 21:25:05 +00003740Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003741 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003742 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003743 // C++0x [temp.deduct.type]p9:
3744 // If the template argument list of P contains a pack expansion that is not
3745 // the last template argument, the entire template argument list is a
3746 // non-deduced context.
3747 if (OnlyDeduced &&
3748 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3749 return;
3750
Douglas Gregor031a5882009-06-13 00:26:55 +00003751 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003752 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3753 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003754}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003755
3756/// \brief Marks all of the template parameters that will be deduced by a
3757/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003758void
3759Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3760 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003761 TemplateParameterList *TemplateParams
3762 = FunctionTemplate->getTemplateParameters();
3763 Deduced.clear();
3764 Deduced.resize(TemplateParams->size());
3765
3766 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3767 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3768 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003769 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003770}