blob: 842ad5c188c1eaabbe5706c05de27b42b9d09ac6 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregord3731192011-01-10 07:32:04 +0000481/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000482static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000483getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000484 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
485 return std::make_pair(TTP->getDepth(), TTP->getIndex());
486
487 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
488 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
489
490 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
491 return std::make_pair(TTP->getDepth(), TTP->getIndex());
492}
493
Douglas Gregord3731192011-01-10 07:32:04 +0000494/// \brief Retrieve the depth and index of an unexpanded parameter pack.
495static std::pair<unsigned, unsigned>
496getDepthAndIndex(UnexpandedParameterPack UPP) {
497 if (const TemplateTypeParmType *TTP
498 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
499 return std::make_pair(TTP->getDepth(), TTP->getIndex());
500
501 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
502}
503
Douglas Gregor603cfb42011-01-05 23:12:31 +0000504/// \brief Helper function to build a TemplateParameter when we don't
505/// know its type statically.
506static TemplateParameter makeTemplateParameter(Decl *D) {
507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
508 return TemplateParameter(TTP);
509 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
510 return TemplateParameter(NTTP);
511
512 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
513}
514
Douglas Gregor54293852011-01-10 17:35:05 +0000515/// \brief Prepare to perform template argument deduction for all of the
516/// arguments in a set of argument packs.
517static void PrepareArgumentPackDeduction(Sema &S,
518 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
519 const llvm::SmallVectorImpl<unsigned> &PackIndices,
520 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
521 llvm::SmallVectorImpl<
522 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
523 // Save the deduced template arguments for each parameter pack expanded
524 // by this pack expansion, then clear out the deduction.
525 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
526 // Save the previously-deduced argument pack, then clear it out so that we
527 // can deduce a new argument pack.
528 SavedPacks[I] = Deduced[PackIndices[I]];
529 Deduced[PackIndices[I]] = TemplateArgument();
530
531 // If the template arugment pack was explicitly specified, add that to
532 // the set of deduced arguments.
533 const TemplateArgument *ExplicitArgs;
534 unsigned NumExplicitArgs;
535 if (NamedDecl *PartiallySubstitutedPack
536 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
537 &ExplicitArgs,
538 &NumExplicitArgs)) {
539 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
540 NewlyDeducedPacks[I].append(ExplicitArgs,
541 ExplicitArgs + NumExplicitArgs);
542 }
543 }
544}
545
Douglas Gregor0216f812011-01-10 17:53:52 +0000546/// \brief Finish template argument deduction for a set of argument packs,
547/// producing the argument packs and checking for consistency with prior
548/// deductions.
549static Sema::TemplateDeductionResult
550FinishArgumentPackDeduction(Sema &S,
551 TemplateParameterList *TemplateParams,
552 bool HasAnyArguments,
553 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
554 const llvm::SmallVectorImpl<unsigned> &PackIndices,
555 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
556 llvm::SmallVectorImpl<
557 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
558 TemplateDeductionInfo &Info) {
559 // Build argument packs for each of the parameter packs expanded by this
560 // pack expansion.
561 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
562 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
563 // We were not able to deduce anything for this parameter pack,
564 // so just restore the saved argument pack.
565 Deduced[PackIndices[I]] = SavedPacks[I];
566 continue;
567 }
568
569 DeducedTemplateArgument NewPack;
570
571 if (NewlyDeducedPacks[I].empty()) {
572 // If we deduced an empty argument pack, create it now.
573 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
574 } else {
575 TemplateArgument *ArgumentPack
576 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
577 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
578 ArgumentPack);
579 NewPack
580 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
581 NewlyDeducedPacks[I].size()),
582 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
583 }
584
585 DeducedTemplateArgument Result
586 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
587 if (Result.isNull()) {
588 Info.Param
589 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
590 Info.FirstArg = SavedPacks[I];
591 Info.SecondArg = NewPack;
592 return Sema::TDK_Inconsistent;
593 }
594
595 Deduced[PackIndices[I]] = Result;
596 }
597
598 return Sema::TDK_Success;
599}
600
Douglas Gregor603cfb42011-01-05 23:12:31 +0000601/// \brief Deduce the template arguments by comparing the list of parameter
602/// types to the list of argument types, as in the parameter-type-lists of
603/// function types (C++ [temp.deduct.type]p10).
604///
605/// \param S The semantic analysis object within which we are deducing
606///
607/// \param TemplateParams The template parameters that we are deducing
608///
609/// \param Params The list of parameter types
610///
611/// \param NumParams The number of types in \c Params
612///
613/// \param Args The list of argument types
614///
615/// \param NumArgs The number of types in \c Args
616///
617/// \param Info information about the template argument deduction itself
618///
619/// \param Deduced the deduced template arguments
620///
621/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
622/// how template argument deduction is performed.
623///
624/// \returns the result of template argument deduction so far. Note that a
625/// "success" result means that template argument deduction has not yet failed,
626/// but it may still fail, later, for other reasons.
627static Sema::TemplateDeductionResult
628DeduceTemplateArguments(Sema &S,
629 TemplateParameterList *TemplateParams,
630 const QualType *Params, unsigned NumParams,
631 const QualType *Args, unsigned NumArgs,
632 TemplateDeductionInfo &Info,
633 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
634 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000635 // Fast-path check to see if we have too many/too few arguments.
636 if (NumParams != NumArgs &&
637 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
638 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000639 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000640
641 // C++0x [temp.deduct.type]p10:
642 // Similarly, if P has a form that contains (T), then each parameter type
643 // Pi of the respective parameter-type- list of P is compared with the
644 // corresponding parameter type Ai of the corresponding parameter-type-list
645 // of A. [...]
646 unsigned ArgIdx = 0, ParamIdx = 0;
647 for (; ParamIdx != NumParams; ++ParamIdx) {
648 // Check argument types.
649 const PackExpansionType *Expansion
650 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
651 if (!Expansion) {
652 // Simple case: compare the parameter and argument types at this point.
653
654 // Make sure we have an argument.
655 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000656 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000657
658 if (Sema::TemplateDeductionResult Result
659 = DeduceTemplateArguments(S, TemplateParams,
660 Params[ParamIdx],
661 Args[ArgIdx],
662 Info, Deduced, TDF))
663 return Result;
664
665 ++ArgIdx;
666 continue;
667 }
668
669 // C++0x [temp.deduct.type]p10:
670 // If the parameter-declaration corresponding to Pi is a function
671 // parameter pack, then the type of its declarator- id is compared with
672 // each remaining parameter type in the parameter-type-list of A. Each
673 // comparison deduces template arguments for subsequent positions in the
674 // template parameter packs expanded by the function parameter pack.
675
676 // Compute the set of template parameter indices that correspond to
677 // parameter packs expanded by the pack expansion.
678 llvm::SmallVector<unsigned, 2> PackIndices;
679 QualType Pattern = Expansion->getPattern();
680 {
681 llvm::BitVector SawIndices(TemplateParams->size());
682 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
683 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
684 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
685 unsigned Depth, Index;
686 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
687 if (Depth == 0 && !SawIndices[Index]) {
688 SawIndices[Index] = true;
689 PackIndices.push_back(Index);
690 }
691 }
692 }
693 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
694
Douglas Gregord3731192011-01-10 07:32:04 +0000695 // Keep track of the deduced template arguments for each parameter pack
696 // expanded by this pack expansion (the outer index) and for each
697 // template argument (the inner SmallVectors).
698 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
699 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000700 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000701 SavedPacks(PackIndices.size());
702 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
703 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000704
Douglas Gregor603cfb42011-01-05 23:12:31 +0000705 bool HasAnyArguments = false;
706 for (; ArgIdx < NumArgs; ++ArgIdx) {
707 HasAnyArguments = true;
708
709 // Deduce template arguments from the pattern.
710 if (Sema::TemplateDeductionResult Result
711 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
712 Info, Deduced))
713 return Result;
714
715 // Capture the deduced template arguments for each parameter pack expanded
716 // by this pack expansion, add them to the list of arguments we've deduced
717 // for that pack, then clear out the deduced argument.
718 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
719 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
720 if (!DeducedArg.isNull()) {
721 NewlyDeducedPacks[I].push_back(DeducedArg);
722 DeducedArg = DeducedTemplateArgument();
723 }
724 }
725 }
726
727 // Build argument packs for each of the parameter packs expanded by this
728 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000729 if (Sema::TemplateDeductionResult Result
730 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
731 Deduced, PackIndices, SavedPacks,
732 NewlyDeducedPacks, Info))
733 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000734 }
735
736 // Make sure we don't have any extra arguments.
737 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000738 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000739
740 return Sema::TDK_Success;
741}
742
Douglas Gregor500d3312009-06-26 18:27:22 +0000743/// \brief Deduce the template arguments by comparing the parameter type and
744/// the argument type (C++ [temp.deduct.type]).
745///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000746/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000747///
748/// \param TemplateParams the template parameters that we are deducing
749///
750/// \param ParamIn the parameter type
751///
752/// \param ArgIn the argument type
753///
754/// \param Info information about the template argument deduction itself
755///
756/// \param Deduced the deduced template arguments
757///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000758/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000759/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000760///
761/// \returns the result of template argument deduction so far. Note that a
762/// "success" result means that template argument deduction has not yet failed,
763/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000764static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000765DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000766 TemplateParameterList *TemplateParams,
767 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000768 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000769 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000770 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000771 // We only want to look at the canonical types, since typedefs and
772 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000773 QualType Param = S.Context.getCanonicalType(ParamIn);
774 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000775
Douglas Gregor500d3312009-06-26 18:27:22 +0000776 // C++0x [temp.deduct.call]p4 bullet 1:
777 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000778 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000779 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000780 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000781 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000782 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000783 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
784 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000785 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000788 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000789 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000790 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000791 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000792
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000793 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000794 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000795
Douglas Gregor199d9912009-06-05 00:53:49 +0000796 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000797 // A template type argument T, a template template argument TT or a
798 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000799 // the following forms:
800 //
801 // T
802 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000803 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000804 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000805 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000806 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000808 // If the argument type is an array type, move the qualifiers up to the
809 // top level, so they can be matched with the qualifiers on the parameter.
810 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000811 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000812 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000813 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000814 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000815 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000816 RecanonicalizeArg = true;
817 }
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000820 // The argument type can not be less qualified than the parameter
821 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000822 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000823 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000824 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000825 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000826 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000827 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000828
829 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000830 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000831 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000832
833 // local manipulation is okay because it's canonical
834 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000835 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000836 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000838 DeducedTemplateArgument NewDeduced(DeducedType);
839 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
840 Deduced[Index],
841 NewDeduced);
842 if (Result.isNull()) {
843 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
844 Info.FirstArg = Deduced[Index];
845 Info.SecondArg = NewDeduced;
846 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000847 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000848
849 Deduced[Index] = Result;
850 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000851 }
852
Douglas Gregorf67875d2009-06-12 18:26:56 +0000853 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000854 Info.FirstArg = TemplateArgument(ParamIn);
855 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000856
Douglas Gregor508f1c82009-06-26 23:10:12 +0000857 // Check the cv-qualifiers on the parameter and argument types.
858 if (!(TDF & TDF_IgnoreQualifiers)) {
859 if (TDF & TDF_ParamWithReferenceType) {
860 if (Param.isMoreQualifiedThan(Arg))
861 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000862 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000863 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000864 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000865 }
866 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000867
Douglas Gregord560d502009-06-04 00:21:18 +0000868 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000869 // No deduction possible for these types
870 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000871 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Douglas Gregor199d9912009-06-05 00:53:49 +0000873 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000874 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000875 QualType PointeeType;
876 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
877 PointeeType = PointerArg->getPointeeType();
878 } else if (const ObjCObjectPointerType *PointerArg
879 = Arg->getAs<ObjCObjectPointerType>()) {
880 PointeeType = PointerArg->getPointeeType();
881 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000882 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000883 }
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregor41128772009-06-26 23:27:24 +0000885 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000886 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000887 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000888 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000889 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregor199d9912009-06-05 00:53:49 +0000892 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000893 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000894 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000895 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000896 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000899 cast<LValueReferenceType>(Param)->getPointeeType(),
900 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000901 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000902 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000903
Douglas Gregor199d9912009-06-05 00:53:49 +0000904 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000905 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000906 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000907 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000908 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000910 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000911 cast<RValueReferenceType>(Param)->getPointeeType(),
912 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000913 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor199d9912009-06-05 00:53:49 +0000916 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000917 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000918 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000919 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000920 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000921 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
John McCalle4f26e52010-08-19 00:20:19 +0000923 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000924 return DeduceTemplateArguments(S, TemplateParams,
925 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000926 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000927 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000928 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000929
930 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000931 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000932 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000933 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000934 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000935 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
937 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000938 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000939 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000940 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000941
John McCalle4f26e52010-08-19 00:20:19 +0000942 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000943 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000944 ConstantArrayParm->getElementType(),
945 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000946 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000947 }
948
Douglas Gregor199d9912009-06-05 00:53:49 +0000949 // type [i]
950 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000951 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000952 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000953 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
John McCalle4f26e52010-08-19 00:20:19 +0000955 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
956
Douglas Gregor199d9912009-06-05 00:53:49 +0000957 // Check the element type of the arrays
958 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000959 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000960 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000961 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000962 DependentArrayParm->getElementType(),
963 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000964 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Douglas Gregor199d9912009-06-05 00:53:49 +0000967 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000968 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000969 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
970 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000971 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000972
973 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000974 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000975 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000976 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000977 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000978 = dyn_cast<ConstantArrayType>(ArrayArg)) {
979 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000980 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
981 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000982 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000983 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000984 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000985 if (const DependentSizedArrayType *DependentArrayArg
986 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000987 if (DependentArrayArg->getSizeExpr())
988 return DeduceNonTypeTemplateArgument(S, NTTP,
989 DependentArrayArg->getSizeExpr(),
990 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Douglas Gregor199d9912009-06-05 00:53:49 +0000992 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000993 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
996 // type(*)(T)
997 // T(*)()
998 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000999 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001000 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001001 dyn_cast<FunctionProtoType>(Arg);
1002 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001003 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001004
1005 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001006 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001007
Mike Stump1eb44332009-09-09 15:08:12 +00001008 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001009 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001010 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001012 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001013 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001014
Anders Carlssona27fad52009-06-08 15:19:08 +00001015 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001016 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001017 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001018 FunctionProtoParam->getResultType(),
1019 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001020 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001021 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Douglas Gregor603cfb42011-01-05 23:12:31 +00001023 return DeduceTemplateArguments(S, TemplateParams,
1024 FunctionProtoParam->arg_type_begin(),
1025 FunctionProtoParam->getNumArgs(),
1026 FunctionProtoArg->arg_type_begin(),
1027 FunctionProtoArg->getNumArgs(),
1028 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
John McCall3cb0ebd2010-03-10 03:28:59 +00001031 case Type::InjectedClassName: {
1032 // Treat a template's injected-class-name as if the template
1033 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001034 Param = cast<InjectedClassNameType>(Param)
1035 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001036 assert(isa<TemplateSpecializationType>(Param) &&
1037 "injected class name is not a template specialization type");
1038 // fall through
1039 }
1040
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001041 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001042 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001043 // TT<T>
1044 // TT<i>
1045 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001046 case Type::TemplateSpecialization: {
1047 const TemplateSpecializationType *SpecParam
1048 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001050 // Try to deduce template arguments from the template-id.
1051 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001052 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001053 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001055 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001056 // C++ [temp.deduct.call]p3b3:
1057 // If P is a class, and P has the form template-id, then A can be a
1058 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001059 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001060 // class pointed to by the deduced A.
1061 //
1062 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001063 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001064 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001065 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1066 // We cannot inspect base classes as part of deduction when the type
1067 // is incomplete, so either instantiate any templates necessary to
1068 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001069 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001070 return Result;
1071
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001072 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001073 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001074 // ToVisit is our stack of records that we still need to visit.
1075 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1076 llvm::SmallVector<const RecordType *, 8> ToVisit;
1077 ToVisit.push_back(RecordT);
1078 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001079 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1080 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001081 while (!ToVisit.empty()) {
1082 // Retrieve the next class in the inheritance hierarchy.
1083 const RecordType *NextT = ToVisit.back();
1084 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001086 // If we have already seen this type, skip it.
1087 if (!Visited.insert(NextT))
1088 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001090 // If this is a base class, try to perform template argument
1091 // deduction from it.
1092 if (NextT != RecordT) {
1093 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001094 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001095 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001097 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001098 // note that we had some success. Otherwise, ignore any deductions
1099 // from this base class.
1100 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001101 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001102 DeducedOrig = Deduced;
1103 }
1104 else
1105 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001108 // Visit base classes
1109 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1110 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1111 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001112 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001113 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001114 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001115 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001116 }
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001119 if (Successful)
1120 return Sema::TDK_Success;
1121 }
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001125 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001126 }
1127
Douglas Gregor637a4092009-06-10 23:47:09 +00001128 // T type::*
1129 // T T::*
1130 // T (type::*)()
1131 // type (T::*)()
1132 // type (type::*)(T)
1133 // type (T::*)(T)
1134 // T (type::*)(T)
1135 // T (T::*)()
1136 // T (T::*)(T)
1137 case Type::MemberPointer: {
1138 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1139 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1140 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001141 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001142
Douglas Gregorf67875d2009-06-12 18:26:56 +00001143 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001144 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001145 MemPtrParam->getPointeeType(),
1146 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001147 Info, Deduced,
1148 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001149 return Result;
1150
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001151 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001152 QualType(MemPtrParam->getClass(), 0),
1153 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001154 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001155 }
1156
Anders Carlsson9a917e42009-06-12 22:56:54 +00001157 // (clang extension)
1158 //
Mike Stump1eb44332009-09-09 15:08:12 +00001159 // type(^)(T)
1160 // T(^)()
1161 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001162 case Type::BlockPointer: {
1163 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1164 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Anders Carlsson859ba502009-06-12 16:23:10 +00001166 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001167 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001169 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001170 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001171 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001172 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001173 }
1174
Douglas Gregor637a4092009-06-10 23:47:09 +00001175 case Type::TypeOfExpr:
1176 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001177 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001178 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001179 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001180
Douglas Gregord560d502009-06-04 00:21:18 +00001181 default:
1182 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001183 }
1184
1185 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001186 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001187}
1188
Douglas Gregorf67875d2009-06-12 18:26:56 +00001189static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001190DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001191 TemplateParameterList *TemplateParams,
1192 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001193 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001194 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001195 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001196 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001197 case TemplateArgument::Null:
1198 assert(false && "Null template argument in parameter list");
1199 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
1201 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001202 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001203 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001204 Arg.getAsType(), Info, Deduced, 0);
1205 Info.FirstArg = Param;
1206 Info.SecondArg = Arg;
1207 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001208
Douglas Gregor788cd062009-11-11 01:00:40 +00001209 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001210 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001211 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001212 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001213 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001214 Info.FirstArg = Param;
1215 Info.SecondArg = Arg;
1216 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001217
1218 case TemplateArgument::TemplateExpansion:
1219 llvm_unreachable("caller should handle pack expansions");
1220 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001221
Douglas Gregor199d9912009-06-05 00:53:49 +00001222 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001223 if (Arg.getKind() == TemplateArgument::Declaration &&
1224 Param.getAsDecl()->getCanonicalDecl() ==
1225 Arg.getAsDecl()->getCanonicalDecl())
1226 return Sema::TDK_Success;
1227
Douglas Gregorf67875d2009-06-12 18:26:56 +00001228 Info.FirstArg = Param;
1229 Info.SecondArg = Arg;
1230 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregor199d9912009-06-05 00:53:49 +00001232 case TemplateArgument::Integral:
1233 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001234 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001235 return Sema::TDK_Success;
1236
1237 Info.FirstArg = Param;
1238 Info.SecondArg = Arg;
1239 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001240 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001241
1242 if (Arg.getKind() == TemplateArgument::Expression) {
1243 Info.FirstArg = Param;
1244 Info.SecondArg = Arg;
1245 return Sema::TDK_NonDeducedMismatch;
1246 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001247
Douglas Gregorf67875d2009-06-12 18:26:56 +00001248 Info.FirstArg = Param;
1249 Info.SecondArg = Arg;
1250 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Douglas Gregor199d9912009-06-05 00:53:49 +00001252 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001253 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001254 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1255 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001256 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001257 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001258 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001259 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001260 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001261 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001262 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001263 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001264 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001265 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001266 Info, Deduced);
1267
Douglas Gregorf67875d2009-06-12 18:26:56 +00001268 Info.FirstArg = Param;
1269 Info.SecondArg = Arg;
1270 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001271 }
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Douglas Gregor199d9912009-06-05 00:53:49 +00001273 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001274 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001275 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001276 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001277 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Douglas Gregorf67875d2009-06-12 18:26:56 +00001280 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001281}
1282
Douglas Gregor20a55e22010-12-22 18:17:10 +00001283/// \brief Determine whether there is a template argument to be used for
1284/// deduction.
1285///
1286/// This routine "expands" argument packs in-place, overriding its input
1287/// parameters so that \c Args[ArgIdx] will be the available template argument.
1288///
1289/// \returns true if there is another template argument (which will be at
1290/// \c Args[ArgIdx]), false otherwise.
1291static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1292 unsigned &ArgIdx,
1293 unsigned &NumArgs) {
1294 if (ArgIdx == NumArgs)
1295 return false;
1296
1297 const TemplateArgument &Arg = Args[ArgIdx];
1298 if (Arg.getKind() != TemplateArgument::Pack)
1299 return true;
1300
1301 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1302 Args = Arg.pack_begin();
1303 NumArgs = Arg.pack_size();
1304 ArgIdx = 0;
1305 return ArgIdx < NumArgs;
1306}
1307
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001308/// \brief Determine whether the given set of template arguments has a pack
1309/// expansion that is not the last template argument.
1310static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1311 unsigned NumArgs) {
1312 unsigned ArgIdx = 0;
1313 while (ArgIdx < NumArgs) {
1314 const TemplateArgument &Arg = Args[ArgIdx];
1315
1316 // Unwrap argument packs.
1317 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1318 Args = Arg.pack_begin();
1319 NumArgs = Arg.pack_size();
1320 ArgIdx = 0;
1321 continue;
1322 }
1323
1324 ++ArgIdx;
1325 if (ArgIdx == NumArgs)
1326 return false;
1327
1328 if (Arg.isPackExpansion())
1329 return true;
1330 }
1331
1332 return false;
1333}
1334
Douglas Gregor20a55e22010-12-22 18:17:10 +00001335static Sema::TemplateDeductionResult
1336DeduceTemplateArguments(Sema &S,
1337 TemplateParameterList *TemplateParams,
1338 const TemplateArgument *Params, unsigned NumParams,
1339 const TemplateArgument *Args, unsigned NumArgs,
1340 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001341 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1342 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001343 // C++0x [temp.deduct.type]p9:
1344 // If the template argument list of P contains a pack expansion that is not
1345 // the last template argument, the entire template argument list is a
1346 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001347 if (hasPackExpansionBeforeEnd(Params, NumParams))
1348 return Sema::TDK_Success;
1349
Douglas Gregore02e2622010-12-22 21:19:48 +00001350 // C++0x [temp.deduct.type]p9:
1351 // If P has a form that contains <T> or <i>, then each argument Pi of the
1352 // respective template argument list P is compared with the corresponding
1353 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001354 unsigned ArgIdx = 0, ParamIdx = 0;
1355 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1356 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001357 // FIXME: Variadic templates.
1358 // What do we do if the argument is a pack expansion?
1359
Douglas Gregor20a55e22010-12-22 18:17:10 +00001360 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001361 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001362
1363 // Check whether we have enough arguments.
1364 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001365 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001366 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001367
Douglas Gregore02e2622010-12-22 21:19:48 +00001368 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001369 if (Sema::TemplateDeductionResult Result
1370 = DeduceTemplateArguments(S, TemplateParams,
1371 Params[ParamIdx], Args[ArgIdx],
1372 Info, Deduced))
1373 return Result;
1374
1375 // Move to the next argument.
1376 ++ArgIdx;
1377 continue;
1378 }
1379
Douglas Gregore02e2622010-12-22 21:19:48 +00001380 // The parameter is a pack expansion.
1381
1382 // C++0x [temp.deduct.type]p9:
1383 // If Pi is a pack expansion, then the pattern of Pi is compared with
1384 // each remaining argument in the template argument list of A. Each
1385 // comparison deduces template arguments for subsequent positions in the
1386 // template parameter packs expanded by Pi.
1387 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1388
1389 // Compute the set of template parameter indices that correspond to
1390 // parameter packs expanded by the pack expansion.
1391 llvm::SmallVector<unsigned, 2> PackIndices;
1392 {
1393 llvm::BitVector SawIndices(TemplateParams->size());
1394 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1395 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1396 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1397 unsigned Depth, Index;
1398 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1399 if (Depth == 0 && !SawIndices[Index]) {
1400 SawIndices[Index] = true;
1401 PackIndices.push_back(Index);
1402 }
1403 }
1404 }
1405 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1406
1407 // FIXME: If there are no remaining arguments, we can bail out early
1408 // and set any deduced parameter packs to an empty argument pack.
1409 // The latter part of this is a (minor) correctness issue.
1410
1411 // Save the deduced template arguments for each parameter pack expanded
1412 // by this pack expansion, then clear out the deduction.
1413 llvm::SmallVector<DeducedTemplateArgument, 2>
1414 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001415 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1416 NewlyDeducedPacks(PackIndices.size());
1417 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1418 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001419
1420 // Keep track of the deduced template arguments for each parameter pack
1421 // expanded by this pack expansion (the outer index) and for each
1422 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001423 bool HasAnyArguments = false;
1424 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1425 HasAnyArguments = true;
1426
1427 // Deduce template arguments from the pattern.
1428 if (Sema::TemplateDeductionResult Result
1429 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1430 Info, Deduced))
1431 return Result;
1432
1433 // Capture the deduced template arguments for each parameter pack expanded
1434 // by this pack expansion, add them to the list of arguments we've deduced
1435 // for that pack, then clear out the deduced argument.
1436 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1437 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1438 if (!DeducedArg.isNull()) {
1439 NewlyDeducedPacks[I].push_back(DeducedArg);
1440 DeducedArg = DeducedTemplateArgument();
1441 }
1442 }
1443
1444 ++ArgIdx;
1445 }
1446
1447 // Build argument packs for each of the parameter packs expanded by this
1448 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001449 if (Sema::TemplateDeductionResult Result
1450 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1451 Deduced, PackIndices, SavedPacks,
1452 NewlyDeducedPacks, Info))
1453 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001454 }
1455
1456 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001457 if (NumberOfArgumentsMustMatch &&
1458 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001459 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001460
1461 return Sema::TDK_Success;
1462}
1463
Mike Stump1eb44332009-09-09 15:08:12 +00001464static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001465DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001466 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001467 const TemplateArgumentList &ParamList,
1468 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001469 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001470 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001471 return DeduceTemplateArguments(S, TemplateParams,
1472 ParamList.data(), ParamList.size(),
1473 ArgList.data(), ArgList.size(),
1474 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001475}
1476
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001477/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001478static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001479 const TemplateArgument &X,
1480 const TemplateArgument &Y) {
1481 if (X.getKind() != Y.getKind())
1482 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001484 switch (X.getKind()) {
1485 case TemplateArgument::Null:
1486 assert(false && "Comparing NULL template argument");
1487 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001489 case TemplateArgument::Type:
1490 return Context.getCanonicalType(X.getAsType()) ==
1491 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001493 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001494 return X.getAsDecl()->getCanonicalDecl() ==
1495 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Douglas Gregor788cd062009-11-11 01:00:40 +00001497 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001498 case TemplateArgument::TemplateExpansion:
1499 return Context.getCanonicalTemplateName(
1500 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1501 Context.getCanonicalTemplateName(
1502 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001503
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001504 case TemplateArgument::Integral:
1505 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor788cd062009-11-11 01:00:40 +00001507 case TemplateArgument::Expression: {
1508 llvm::FoldingSetNodeID XID, YID;
1509 X.getAsExpr()->Profile(XID, Context, true);
1510 Y.getAsExpr()->Profile(YID, Context, true);
1511 return XID == YID;
1512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001514 case TemplateArgument::Pack:
1515 if (X.pack_size() != Y.pack_size())
1516 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001517
1518 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1519 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001520 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001521 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001522 if (!isSameTemplateArg(Context, *XP, *YP))
1523 return false;
1524
1525 return true;
1526 }
1527
1528 return false;
1529}
1530
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001531/// \brief Allocate a TemplateArgumentLoc where all locations have
1532/// been initialized to the given location.
1533///
1534/// \param S The semantic analysis object.
1535///
1536/// \param The template argument we are producing template argument
1537/// location information for.
1538///
1539/// \param NTTPType For a declaration template argument, the type of
1540/// the non-type template parameter that corresponds to this template
1541/// argument.
1542///
1543/// \param Loc The source location to use for the resulting template
1544/// argument.
1545static TemplateArgumentLoc
1546getTrivialTemplateArgumentLoc(Sema &S,
1547 const TemplateArgument &Arg,
1548 QualType NTTPType,
1549 SourceLocation Loc) {
1550 switch (Arg.getKind()) {
1551 case TemplateArgument::Null:
1552 llvm_unreachable("Can't get a NULL template argument here");
1553 break;
1554
1555 case TemplateArgument::Type:
1556 return TemplateArgumentLoc(Arg,
1557 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1558
1559 case TemplateArgument::Declaration: {
1560 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001561 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001562 .takeAs<Expr>();
1563 return TemplateArgumentLoc(TemplateArgument(E), E);
1564 }
1565
1566 case TemplateArgument::Integral: {
1567 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001568 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001569 return TemplateArgumentLoc(TemplateArgument(E), E);
1570 }
1571
1572 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001573 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1574
1575 case TemplateArgument::TemplateExpansion:
1576 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1577
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001578 case TemplateArgument::Expression:
1579 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1580
1581 case TemplateArgument::Pack:
1582 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1583 }
1584
1585 return TemplateArgumentLoc();
1586}
1587
1588
1589/// \brief Convert the given deduced template argument and add it to the set of
1590/// fully-converted template arguments.
1591static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1592 DeducedTemplateArgument Arg,
1593 NamedDecl *Template,
1594 QualType NTTPType,
1595 TemplateDeductionInfo &Info,
1596 bool InFunctionTemplate,
1597 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1598 if (Arg.getKind() == TemplateArgument::Pack) {
1599 // This is a template argument pack, so check each of its arguments against
1600 // the template parameter.
1601 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1602 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001603 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001604 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001605 // When converting the deduced template argument, append it to the
1606 // general output list. We need to do this so that the template argument
1607 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001608 DeducedTemplateArgument InnerArg(*PA);
1609 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1610 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1611 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001612 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001613 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001614
1615 // Move the converted template argument into our argument pack.
1616 PackedArgsBuilder.push_back(Output.back());
1617 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001618 }
1619
1620 // Create the resulting argument pack.
1621 TemplateArgument *PackedArgs = 0;
1622 if (!PackedArgsBuilder.empty()) {
1623 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1624 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1625 }
1626 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1627 return false;
1628 }
1629
1630 // Convert the deduced template argument into a template
1631 // argument that we can check, almost as if the user had written
1632 // the template argument explicitly.
1633 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1634 Info.getLocation());
1635
1636 // Check the template argument, converting it as necessary.
1637 return S.CheckTemplateArgument(Param, ArgLoc,
1638 Template,
1639 Template->getLocation(),
1640 Template->getSourceRange().getEnd(),
1641 Output,
1642 InFunctionTemplate
1643 ? (Arg.wasDeducedFromArrayBound()
1644 ? Sema::CTAK_DeducedFromArrayBound
1645 : Sema::CTAK_Deduced)
1646 : Sema::CTAK_Specified);
1647}
1648
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001649/// Complete template argument deduction for a class template partial
1650/// specialization.
1651static Sema::TemplateDeductionResult
1652FinishTemplateArgumentDeduction(Sema &S,
1653 ClassTemplatePartialSpecializationDecl *Partial,
1654 const TemplateArgumentList &TemplateArgs,
1655 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001656 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001657 // Trap errors.
1658 Sema::SFINAETrap Trap(S);
1659
1660 Sema::ContextRAII SavedContext(S, Partial);
1661
1662 // C++ [temp.deduct.type]p2:
1663 // [...] or if any template argument remains neither deduced nor
1664 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001665 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001666 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1667 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001668 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001669 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001670 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001671 return Sema::TDK_Incomplete;
1672 }
1673
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001674 // We have deduced this argument, so it still needs to be
1675 // checked and converted.
1676
1677 // First, for a non-type template parameter type that is
1678 // initialized by a declaration, we need the type of the
1679 // corresponding non-type template parameter.
1680 QualType NTTPType;
1681 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001682 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001683 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001684 if (NTTPType->isDependentType()) {
1685 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1686 Builder.data(), Builder.size());
1687 NTTPType = S.SubstType(NTTPType,
1688 MultiLevelTemplateArgumentList(TemplateArgs),
1689 NTTP->getLocation(),
1690 NTTP->getDeclName());
1691 if (NTTPType.isNull()) {
1692 Info.Param = makeTemplateParameter(Param);
1693 // FIXME: These template arguments are temporary. Free them!
1694 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1695 Builder.data(),
1696 Builder.size()));
1697 return Sema::TDK_SubstitutionFailure;
1698 }
1699 }
1700 }
1701
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001702 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1703 Partial, NTTPType, Info, false,
1704 Builder)) {
1705 Info.Param = makeTemplateParameter(Param);
1706 // FIXME: These template arguments are temporary. Free them!
1707 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1708 Builder.size()));
1709 return Sema::TDK_SubstitutionFailure;
1710 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001711 }
1712
1713 // Form the template argument list from the deduced template arguments.
1714 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001715 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1716 Builder.size());
1717
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001718 Info.reset(DeducedArgumentList);
1719
1720 // Substitute the deduced template arguments into the template
1721 // arguments of the class template partial specialization, and
1722 // verify that the instantiated template arguments are both valid
1723 // and are equivalent to the template arguments originally provided
1724 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001725 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001726 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1727 const TemplateArgumentLoc *PartialTemplateArgs
1728 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001729
1730 // Note that we don't provide the langle and rangle locations.
1731 TemplateArgumentListInfo InstArgs;
1732
Douglas Gregore02e2622010-12-22 21:19:48 +00001733 if (S.Subst(PartialTemplateArgs,
1734 Partial->getNumTemplateArgsAsWritten(),
1735 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1736 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1737 if (ParamIdx >= Partial->getTemplateParameters()->size())
1738 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1739
1740 Decl *Param
1741 = const_cast<NamedDecl *>(
1742 Partial->getTemplateParameters()->getParam(ParamIdx));
1743 Info.Param = makeTemplateParameter(Param);
1744 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1745 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001746 }
1747
Douglas Gregor910f8002010-11-07 23:05:16 +00001748 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001749 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001750 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001751 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001752
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001753 TemplateParameterList *TemplateParams
1754 = ClassTemplate->getTemplateParameters();
1755 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001756 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001757 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001758 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001759 Info.FirstArg = TemplateArgs[I];
1760 Info.SecondArg = InstArg;
1761 return Sema::TDK_NonDeducedMismatch;
1762 }
1763 }
1764
1765 if (Trap.hasErrorOccurred())
1766 return Sema::TDK_SubstitutionFailure;
1767
1768 return Sema::TDK_Success;
1769}
1770
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001771/// \brief Perform template argument deduction to determine whether
1772/// the given template arguments match the given class template
1773/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001774Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001775Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001776 const TemplateArgumentList &TemplateArgs,
1777 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001778 // C++ [temp.class.spec.match]p2:
1779 // A partial specialization matches a given actual template
1780 // argument list if the template arguments of the partial
1781 // specialization can be deduced from the actual template argument
1782 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001783 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001784 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001785 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001786 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001787 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001788 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001789 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001790 TemplateArgs, Info, Deduced))
1791 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001792
Douglas Gregor637a4092009-06-10 23:47:09 +00001793 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001794 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001795 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001796 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001797
Douglas Gregorbb260412009-06-14 08:02:22 +00001798 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001799 return Sema::TDK_SubstitutionFailure;
1800
1801 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1802 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001803}
Douglas Gregor031a5882009-06-13 00:26:55 +00001804
Douglas Gregor41128772009-06-26 23:27:24 +00001805/// \brief Determine whether the given type T is a simple-template-id type.
1806static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001807 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001808 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001809 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Douglas Gregor41128772009-06-26 23:27:24 +00001811 return false;
1812}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001813
1814/// \brief Substitute the explicitly-provided template arguments into the
1815/// given function template according to C++ [temp.arg.explicit].
1816///
1817/// \param FunctionTemplate the function template into which the explicit
1818/// template arguments will be substituted.
1819///
Mike Stump1eb44332009-09-09 15:08:12 +00001820/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001821/// arguments.
1822///
Mike Stump1eb44332009-09-09 15:08:12 +00001823/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001824/// with the converted and checked explicit template arguments.
1825///
Mike Stump1eb44332009-09-09 15:08:12 +00001826/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001827/// parameters.
1828///
1829/// \param FunctionType if non-NULL, the result type of the function template
1830/// will also be instantiated and the pointed-to value will be updated with
1831/// the instantiated function type.
1832///
1833/// \param Info if substitution fails for any reason, this object will be
1834/// populated with more information about the failure.
1835///
1836/// \returns TDK_Success if substitution was successful, or some failure
1837/// condition.
1838Sema::TemplateDeductionResult
1839Sema::SubstituteExplicitTemplateArguments(
1840 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001841 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001842 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001843 llvm::SmallVectorImpl<QualType> &ParamTypes,
1844 QualType *FunctionType,
1845 TemplateDeductionInfo &Info) {
1846 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1847 TemplateParameterList *TemplateParams
1848 = FunctionTemplate->getTemplateParameters();
1849
John McCalld5532b62009-11-23 01:53:49 +00001850 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001851 // No arguments to substitute; just copy over the parameter types and
1852 // fill in the function type.
1853 for (FunctionDecl::param_iterator P = Function->param_begin(),
1854 PEnd = Function->param_end();
1855 P != PEnd;
1856 ++P)
1857 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Douglas Gregor83314aa2009-07-08 20:55:45 +00001859 if (FunctionType)
1860 *FunctionType = Function->getType();
1861 return TDK_Success;
1862 }
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Douglas Gregor83314aa2009-07-08 20:55:45 +00001864 // Substitution of the explicit template arguments into a function template
1865 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001866 SFINAETrap Trap(*this);
1867
Douglas Gregor83314aa2009-07-08 20:55:45 +00001868 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // Template arguments that are present shall be specified in the
1870 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001871 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001872 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001873 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001874
1875 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001876 // explicitly-specified template arguments against this function template,
1877 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001878 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001879 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001880 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1881 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001882 if (Inst)
1883 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Douglas Gregor83314aa2009-07-08 20:55:45 +00001885 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001886 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001887 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001888 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001889 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001890 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001891 if (Index >= TemplateParams->size())
1892 Index = TemplateParams->size() - 1;
1893 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001894 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregor83314aa2009-07-08 20:55:45 +00001897 // Form the template argument list from the explicitly-specified
1898 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001899 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001900 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001901 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001902
John McCalldf41f182010-10-12 19:40:14 +00001903 // Template argument deduction and the final substitution should be
1904 // done in the context of the templated declaration. Explicit
1905 // argument substitution, on the other hand, needs to happen in the
1906 // calling context.
1907 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1908
Douglas Gregord3731192011-01-10 07:32:04 +00001909 // If we deduced template arguments for a template parameter pack,
1910 // note that the template argument pack is partially substituted and record
1911 // the explicit template arguments. They'll be used as part of deduction
1912 // for this template parameter pack.
1913 bool HasPartiallySubstitutedPack = false;
1914 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1915 const TemplateArgument &Arg = Builder[I];
1916 if (Arg.getKind() == TemplateArgument::Pack) {
1917 HasPartiallySubstitutedPack = true;
1918 CurrentInstantiationScope->SetPartiallySubstitutedPack(
1919 TemplateParams->getParam(I),
1920 Arg.pack_begin(),
1921 Arg.pack_size());
1922 break;
1923 }
1924 }
1925
Douglas Gregor83314aa2009-07-08 20:55:45 +00001926 // Instantiate the types of each of the function parameters given the
1927 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001928 if (SubstParmTypes(Function->getLocation(),
1929 Function->param_begin(), Function->getNumParams(),
1930 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1931 ParamTypes))
1932 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001933
1934 // If the caller wants a full function type back, instantiate the return
1935 // type and form that function type.
1936 if (FunctionType) {
1937 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001938 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001939 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001940 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001941
1942 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001943 = SubstType(Proto->getResultType(),
1944 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1945 Function->getTypeSpecStartLoc(),
1946 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001947 if (ResultType.isNull() || Trap.hasErrorOccurred())
1948 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001949
1950 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001951 ParamTypes.data(), ParamTypes.size(),
1952 Proto->isVariadic(),
1953 Proto->getTypeQuals(),
1954 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001955 Function->getDeclName(),
1956 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001957 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1958 return TDK_SubstitutionFailure;
1959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Douglas Gregor83314aa2009-07-08 20:55:45 +00001961 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001962 // Trailing template arguments that can be deduced (14.8.2) may be
1963 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001964 // template arguments can be deduced, they may all be omitted; in this
1965 // case, the empty template argument list <> itself may also be omitted.
1966 //
Douglas Gregord3731192011-01-10 07:32:04 +00001967 // Take all of the explicitly-specified arguments and put them into
1968 // the set of deduced template arguments. Explicitly-specified
1969 // parameter packs, however, will be set to NULL since the deduction
1970 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001971 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00001972 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
1973 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
1974 if (Arg.getKind() == TemplateArgument::Pack)
1975 Deduced.push_back(DeducedTemplateArgument());
1976 else
1977 Deduced.push_back(Arg);
1978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor83314aa2009-07-08 20:55:45 +00001980 return TDK_Success;
1981}
1982
Mike Stump1eb44332009-09-09 15:08:12 +00001983/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001984/// checking the deduced template arguments for completeness and forming
1985/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001986Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001987Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001988 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1989 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001990 FunctionDecl *&Specialization,
1991 TemplateDeductionInfo &Info) {
1992 TemplateParameterList *TemplateParams
1993 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Douglas Gregor83314aa2009-07-08 20:55:45 +00001995 // Template argument deduction for function templates in a SFINAE context.
1996 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001997 SFINAETrap Trap(*this);
1998
Douglas Gregor83314aa2009-07-08 20:55:45 +00001999 // Enter a new template instantiation context while we instantiate the
2000 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002001 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002002 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002003 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2004 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002005 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002006 return TDK_InstantiationDepth;
2007
John McCall96db3102010-04-29 01:18:58 +00002008 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002009
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002010 // C++ [temp.deduct.type]p2:
2011 // [...] or if any template argument remains neither deduced nor
2012 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002013 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002014 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2015 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002016
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002017 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002018 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002019 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002020 // argument, because it was explicitly-specified. Just record the
2021 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002022 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002023 continue;
2024 }
2025
2026 // We have deduced this argument, so it still needs to be
2027 // checked and converted.
2028
2029 // First, for a non-type template parameter type that is
2030 // initialized by a declaration, we need the type of the
2031 // corresponding non-type template parameter.
2032 QualType NTTPType;
2033 if (NonTypeTemplateParmDecl *NTTP
2034 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002035 NTTPType = NTTP->getType();
2036 if (NTTPType->isDependentType()) {
2037 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2038 Builder.data(), Builder.size());
2039 NTTPType = SubstType(NTTPType,
2040 MultiLevelTemplateArgumentList(TemplateArgs),
2041 NTTP->getLocation(),
2042 NTTP->getDeclName());
2043 if (NTTPType.isNull()) {
2044 Info.Param = makeTemplateParameter(Param);
2045 // FIXME: These template arguments are temporary. Free them!
2046 Info.reset(TemplateArgumentList::CreateCopy(Context,
2047 Builder.data(),
2048 Builder.size()));
2049 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002050 }
2051 }
2052 }
2053
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002054 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2055 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002056 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002057 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002058 // FIXME: These template arguments are temporary. Free them!
2059 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002060 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002061 return TDK_SubstitutionFailure;
2062 }
2063
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002064 continue;
2065 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002066
2067 // C++0x [temp.arg.explicit]p3:
2068 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2069 // be deduced to an empty sequence of template arguments.
2070 // FIXME: Where did the word "trailing" come from?
2071 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002072 // We may have had explicitly-specified template arguments for this
2073 // template parameter pack. If so, our empty deduction extends the
2074 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2075 const TemplateArgument *ExplicitArgs;
2076 unsigned NumExplicitArgs;
2077 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2078 &NumExplicitArgs)
2079 == Param)
2080 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2081 else
2082 Builder.push_back(TemplateArgument(0, 0));
2083
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002084 continue;
2085 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002086
2087 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002088 TemplateArgumentLoc DefArg
2089 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2090 FunctionTemplate->getLocation(),
2091 FunctionTemplate->getSourceRange().getEnd(),
2092 Param,
2093 Builder);
2094
2095 // If there was no default argument, deduction is incomplete.
2096 if (DefArg.getArgument().isNull()) {
2097 Info.Param = makeTemplateParameter(
2098 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2099 return TDK_Incomplete;
2100 }
2101
2102 // Check whether we can actually use the default argument.
2103 if (CheckTemplateArgument(Param, DefArg,
2104 FunctionTemplate,
2105 FunctionTemplate->getLocation(),
2106 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002107 Builder,
2108 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002109 Info.Param = makeTemplateParameter(
2110 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002111 // FIXME: These template arguments are temporary. Free them!
2112 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2113 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002114 return TDK_SubstitutionFailure;
2115 }
2116
2117 // If we get here, we successfully used the default template argument.
2118 }
2119
2120 // Form the template argument list from the deduced template arguments.
2121 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002122 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002123 Info.reset(DeducedArgumentList);
2124
Mike Stump1eb44332009-09-09 15:08:12 +00002125 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002126 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002127 DeclContext *Owner = FunctionTemplate->getDeclContext();
2128 if (FunctionTemplate->getFriendObjectKind())
2129 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002130 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002131 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002132 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002133 if (!Specialization)
2134 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Douglas Gregorf8825742009-09-15 18:26:13 +00002136 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2137 FunctionTemplate->getCanonicalDecl());
2138
Mike Stump1eb44332009-09-09 15:08:12 +00002139 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002140 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002141 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2142 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002143 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregor83314aa2009-07-08 20:55:45 +00002145 // There may have been an error that did not prevent us from constructing a
2146 // declaration. Mark the declaration invalid and return with a substitution
2147 // failure.
2148 if (Trap.hasErrorOccurred()) {
2149 Specialization->setInvalidDecl(true);
2150 return TDK_SubstitutionFailure;
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Douglas Gregor9b623632010-10-12 23:32:35 +00002153 // If we suppressed any diagnostics while performing template argument
2154 // deduction, and if we haven't already instantiated this declaration,
2155 // keep track of these diagnostics. They'll be emitted if this specialization
2156 // is actually used.
2157 if (Info.diag_begin() != Info.diag_end()) {
2158 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2159 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2160 if (Pos == SuppressedDiagnostics.end())
2161 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2162 .append(Info.diag_begin(), Info.diag_end());
2163 }
2164
Mike Stump1eb44332009-09-09 15:08:12 +00002165 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002166}
2167
John McCall9c72c602010-08-27 09:08:28 +00002168/// Gets the type of a function for template-argument-deducton
2169/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002170static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002171 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002172 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002173 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002174 if (Method->isInstance()) {
2175 // An instance method that's referenced in a form that doesn't
2176 // look like a member pointer is just invalid.
2177 if (!R.HasFormOfMemberPointer) return QualType();
2178
John McCalleff92132010-02-02 02:21:27 +00002179 return Context.getMemberPointerType(Fn->getType(),
2180 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002181 }
2182
2183 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002184 return Context.getPointerType(Fn->getType());
2185}
2186
2187/// Apply the deduction rules for overload sets.
2188///
2189/// \return the null type if this argument should be treated as an
2190/// undeduced context
2191static QualType
2192ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002193 Expr *Arg, QualType ParamType,
2194 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002195
2196 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002197
John McCall9c72c602010-08-27 09:08:28 +00002198 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002199
Douglas Gregor75f21af2010-08-30 21:04:23 +00002200 // C++0x [temp.deduct.call]p4
2201 unsigned TDF = 0;
2202 if (ParamWasReference)
2203 TDF |= TDF_ParamWithReferenceType;
2204 if (R.IsAddressOfOperand)
2205 TDF |= TDF_IgnoreQualifiers;
2206
John McCalleff92132010-02-02 02:21:27 +00002207 // If there were explicit template arguments, we can only find
2208 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2209 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002210 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002211 // But we can still look for an explicit specialization.
2212 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002213 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002214 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002215 return QualType();
2216 }
2217
2218 // C++0x [temp.deduct.call]p6:
2219 // When P is a function type, pointer to function type, or pointer
2220 // to member function type:
2221
2222 if (!ParamType->isFunctionType() &&
2223 !ParamType->isFunctionPointerType() &&
2224 !ParamType->isMemberFunctionPointerType())
2225 return QualType();
2226
2227 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002228 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2229 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002230 NamedDecl *D = (*I)->getUnderlyingDecl();
2231
2232 // - If the argument is an overload set containing one or more
2233 // function templates, the parameter is treated as a
2234 // non-deduced context.
2235 if (isa<FunctionTemplateDecl>(D))
2236 return QualType();
2237
2238 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002239 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2240 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002241
Douglas Gregor75f21af2010-08-30 21:04:23 +00002242 // Function-to-pointer conversion.
2243 if (!ParamWasReference && ParamType->isPointerType() &&
2244 ArgType->isFunctionType())
2245 ArgType = S.Context.getPointerType(ArgType);
2246
John McCalleff92132010-02-02 02:21:27 +00002247 // - If the argument is an overload set (not containing function
2248 // templates), trial argument deduction is attempted using each
2249 // of the members of the set. If deduction succeeds for only one
2250 // of the overload set members, that member is used as the
2251 // argument value for the deduction. If deduction succeeds for
2252 // more than one member of the overload set the parameter is
2253 // treated as a non-deduced context.
2254
2255 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2256 // Type deduction is done independently for each P/A pair, and
2257 // the deduced template argument values are then combined.
2258 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002259 llvm::SmallVector<DeducedTemplateArgument, 8>
2260 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002261 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002262 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002263 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002264 ParamType, ArgType,
2265 Info, Deduced, TDF);
2266 if (Result) continue;
2267 if (!Match.isNull()) return QualType();
2268 Match = ArgType;
2269 }
2270
2271 return Match;
2272}
2273
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002274/// \brief Perform the adjustments to the parameter and argument types
2275/// described in C++ [temp.deduct.call].
2276///
2277/// \returns true if the caller should not attempt to perform any template
2278/// argument deduction based on this P/A pair.
2279static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2280 TemplateParameterList *TemplateParams,
2281 QualType &ParamType,
2282 QualType &ArgType,
2283 Expr *Arg,
2284 unsigned &TDF) {
2285 // C++0x [temp.deduct.call]p3:
2286 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2287 // are ignored for type deduction.
2288 if (ParamType.getCVRQualifiers())
2289 ParamType = ParamType.getLocalUnqualifiedType();
2290 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2291 if (ParamRefType) {
2292 // [...] If P is a reference type, the type referred to by P is used
2293 // for type deduction.
2294 ParamType = ParamRefType->getPointeeType();
2295 }
2296
2297 // Overload sets usually make this parameter an undeduced
2298 // context, but there are sometimes special circumstances.
2299 if (ArgType == S.Context.OverloadTy) {
2300 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2301 Arg, ParamType,
2302 ParamRefType != 0);
2303 if (ArgType.isNull())
2304 return true;
2305 }
2306
2307 if (ParamRefType) {
2308 // C++0x [temp.deduct.call]p3:
2309 // [...] If P is of the form T&&, where T is a template parameter, and
2310 // the argument is an lvalue, the type A& is used in place of A for
2311 // type deduction.
2312 if (ParamRefType->isRValueReferenceType() &&
2313 ParamRefType->getAs<TemplateTypeParmType>() &&
2314 Arg->isLValue())
2315 ArgType = S.Context.getLValueReferenceType(ArgType);
2316 } else {
2317 // C++ [temp.deduct.call]p2:
2318 // If P is not a reference type:
2319 // - If A is an array type, the pointer type produced by the
2320 // array-to-pointer standard conversion (4.2) is used in place of
2321 // A for type deduction; otherwise,
2322 if (ArgType->isArrayType())
2323 ArgType = S.Context.getArrayDecayedType(ArgType);
2324 // - If A is a function type, the pointer type produced by the
2325 // function-to-pointer standard conversion (4.3) is used in place
2326 // of A for type deduction; otherwise,
2327 else if (ArgType->isFunctionType())
2328 ArgType = S.Context.getPointerType(ArgType);
2329 else {
2330 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2331 // type are ignored for type deduction.
2332 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2333 if (ArgType.getCVRQualifiers())
2334 ArgType = ArgType.getUnqualifiedType();
2335 }
2336 }
2337
2338 // C++0x [temp.deduct.call]p4:
2339 // In general, the deduction process attempts to find template argument
2340 // values that will make the deduced A identical to A (after the type A
2341 // is transformed as described above). [...]
2342 TDF = TDF_SkipNonDependent;
2343
2344 // - If the original P is a reference type, the deduced A (i.e., the
2345 // type referred to by the reference) can be more cv-qualified than
2346 // the transformed A.
2347 if (ParamRefType)
2348 TDF |= TDF_ParamWithReferenceType;
2349 // - The transformed A can be another pointer or pointer to member
2350 // type that can be converted to the deduced A via a qualification
2351 // conversion (4.4).
2352 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2353 ArgType->isObjCObjectPointerType())
2354 TDF |= TDF_IgnoreQualifiers;
2355 // - If P is a class and P has the form simple-template-id, then the
2356 // transformed A can be a derived class of the deduced A. Likewise,
2357 // if P is a pointer to a class of the form simple-template-id, the
2358 // transformed A can be a pointer to a derived class pointed to by
2359 // the deduced A.
2360 if (isSimpleTemplateIdType(ParamType) ||
2361 (isa<PointerType>(ParamType) &&
2362 isSimpleTemplateIdType(
2363 ParamType->getAs<PointerType>()->getPointeeType())))
2364 TDF |= TDF_DerivedClass;
2365
2366 return false;
2367}
2368
Douglas Gregore53060f2009-06-25 22:08:12 +00002369/// \brief Perform template argument deduction from a function call
2370/// (C++ [temp.deduct.call]).
2371///
2372/// \param FunctionTemplate the function template for which we are performing
2373/// template argument deduction.
2374///
Douglas Gregor48026d22010-01-11 18:40:55 +00002375/// \param ExplicitTemplateArguments the explicit template arguments provided
2376/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002377///
Douglas Gregore53060f2009-06-25 22:08:12 +00002378/// \param Args the function call arguments
2379///
2380/// \param NumArgs the number of arguments in Args
2381///
Douglas Gregor48026d22010-01-11 18:40:55 +00002382/// \param Name the name of the function being called. This is only significant
2383/// when the function template is a conversion function template, in which
2384/// case this routine will also perform template argument deduction based on
2385/// the function to which
2386///
Douglas Gregore53060f2009-06-25 22:08:12 +00002387/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002388/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002389/// template argument deduction.
2390///
2391/// \param Info the argument will be updated to provide additional information
2392/// about template argument deduction.
2393///
2394/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002395Sema::TemplateDeductionResult
2396Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002397 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002398 Expr **Args, unsigned NumArgs,
2399 FunctionDecl *&Specialization,
2400 TemplateDeductionInfo &Info) {
2401 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002402
Douglas Gregore53060f2009-06-25 22:08:12 +00002403 // C++ [temp.deduct.call]p1:
2404 // Template argument deduction is done by comparing each function template
2405 // parameter type (call it P) with the type of the corresponding argument
2406 // of the call (call it A) as described below.
2407 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002408 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002409 return TDK_TooFewArguments;
2410 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002411 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002412 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002413 if (Proto->isTemplateVariadic())
2414 /* Do nothing */;
2415 else if (Proto->isVariadic())
2416 CheckArgs = Function->getNumParams();
2417 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002418 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002419 }
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002421 // The types of the parameters from which we will perform template argument
2422 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002423 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002424 TemplateParameterList *TemplateParams
2425 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002426 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002427 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002428 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002429 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002430 TemplateDeductionResult Result =
2431 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002432 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002433 Deduced,
2434 ParamTypes,
2435 0,
2436 Info);
2437 if (Result)
2438 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002439
2440 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002441 } else {
2442 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002443 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002444 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2445 }
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002447 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002448 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002449 unsigned ArgIdx = 0;
2450 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2451 ParamIdx != NumParams; ++ParamIdx) {
2452 QualType ParamType = ParamTypes[ParamIdx];
2453
2454 const PackExpansionType *ParamExpansion
2455 = dyn_cast<PackExpansionType>(ParamType);
2456 if (!ParamExpansion) {
2457 // Simple case: matching a function parameter to a function argument.
2458 if (ArgIdx >= CheckArgs)
2459 break;
2460
2461 Expr *Arg = Args[ArgIdx++];
2462 QualType ArgType = Arg->getType();
2463 unsigned TDF = 0;
2464 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2465 ParamType, ArgType, Arg,
2466 TDF))
2467 continue;
2468
2469 if (TemplateDeductionResult Result
2470 = ::DeduceTemplateArguments(*this, TemplateParams,
2471 ParamType, ArgType, Info, Deduced,
2472 TDF))
2473 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002475 // FIXME: we need to check that the deduced A is the same as A,
2476 // modulo the various allowed differences.
2477 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002478 }
2479
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002480 // C++0x [temp.deduct.call]p1:
2481 // For a function parameter pack that occurs at the end of the
2482 // parameter-declaration-list, the type A of each remaining argument of
2483 // the call is compared with the type P of the declarator-id of the
2484 // function parameter pack. Each comparison deduces template arguments
2485 // for subsequent positions in the template parameter packs expanded by
2486 // the function parameter pack.
2487 QualType ParamPattern = ParamExpansion->getPattern();
2488 llvm::SmallVector<unsigned, 2> PackIndices;
2489 {
2490 llvm::BitVector SawIndices(TemplateParams->size());
2491 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2492 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2493 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2494 unsigned Depth, Index;
2495 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2496 if (Depth == 0 && !SawIndices[Index]) {
2497 SawIndices[Index] = true;
2498 PackIndices.push_back(Index);
2499 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002500 }
2501 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002502 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2503
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002504 // Keep track of the deduced template arguments for each parameter pack
2505 // expanded by this pack expansion (the outer index) and for each
2506 // template argument (the inner SmallVectors).
2507 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002508 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002509 llvm::SmallVector<DeducedTemplateArgument, 2>
2510 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002511 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2512 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002513 bool HasAnyArguments = false;
2514 for (; ArgIdx < NumArgs; ++ArgIdx) {
2515 HasAnyArguments = true;
2516
2517 ParamType = ParamPattern;
2518 Expr *Arg = Args[ArgIdx];
2519 QualType ArgType = Arg->getType();
2520 unsigned TDF = 0;
2521 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2522 ParamType, ArgType, Arg,
2523 TDF)) {
2524 // We can't actually perform any deduction for this argument, so stop
2525 // deduction at this point.
2526 ++ArgIdx;
2527 break;
2528 }
2529
2530 if (TemplateDeductionResult Result
2531 = ::DeduceTemplateArguments(*this, TemplateParams,
2532 ParamType, ArgType, Info, Deduced,
2533 TDF))
2534 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002536 // Capture the deduced template arguments for each parameter pack expanded
2537 // by this pack expansion, add them to the list of arguments we've deduced
2538 // for that pack, then clear out the deduced argument.
2539 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2540 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2541 if (!DeducedArg.isNull()) {
2542 NewlyDeducedPacks[I].push_back(DeducedArg);
2543 DeducedArg = DeducedTemplateArgument();
2544 }
2545 }
2546 }
2547
2548 // Build argument packs for each of the parameter packs expanded by this
2549 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002550 if (Sema::TemplateDeductionResult Result
2551 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2552 Deduced, PackIndices, SavedPacks,
2553 NewlyDeducedPacks, Info))
2554 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002556 // After we've matching against a parameter pack, we're done.
2557 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002558 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002559
Mike Stump1eb44332009-09-09 15:08:12 +00002560 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002561 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002562 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002563}
2564
Douglas Gregor83314aa2009-07-08 20:55:45 +00002565/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002566/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2567/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002568///
2569/// \param FunctionTemplate the function template for which we are performing
2570/// template argument deduction.
2571///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002572/// \param ExplicitTemplateArguments the explicitly-specified template
2573/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002574///
2575/// \param ArgFunctionType the function type that will be used as the
2576/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002577/// function template's function type. This type may be NULL, if there is no
2578/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002579///
2580/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002581/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002582/// template argument deduction.
2583///
2584/// \param Info the argument will be updated to provide additional information
2585/// about template argument deduction.
2586///
2587/// \returns the result of template argument deduction.
2588Sema::TemplateDeductionResult
2589Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002590 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002591 QualType ArgFunctionType,
2592 FunctionDecl *&Specialization,
2593 TemplateDeductionInfo &Info) {
2594 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2595 TemplateParameterList *TemplateParams
2596 = FunctionTemplate->getTemplateParameters();
2597 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor83314aa2009-07-08 20:55:45 +00002599 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002600 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002601 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2602 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002603 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002604 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002605 if (TemplateDeductionResult Result
2606 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002607 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002608 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002609 &FunctionType, Info))
2610 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002611
2612 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002613 }
2614
2615 // Template argument deduction for function templates in a SFINAE context.
2616 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002617 SFINAETrap Trap(*this);
2618
John McCalleff92132010-02-02 02:21:27 +00002619 Deduced.resize(TemplateParams->size());
2620
Douglas Gregor4b52e252009-12-21 23:17:24 +00002621 if (!ArgFunctionType.isNull()) {
2622 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002623 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002624 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002625 FunctionType, ArgFunctionType, Info,
2626 Deduced, 0))
2627 return Result;
2628 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002629
2630 if (TemplateDeductionResult Result
2631 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2632 NumExplicitlySpecified,
2633 Specialization, Info))
2634 return Result;
2635
2636 // If the requested function type does not match the actual type of the
2637 // specialization, template argument deduction fails.
2638 if (!ArgFunctionType.isNull() &&
2639 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2640 return TDK_NonDeducedMismatch;
2641
2642 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002643}
2644
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002645/// \brief Deduce template arguments for a templated conversion
2646/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2647/// conversion function template specialization.
2648Sema::TemplateDeductionResult
2649Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2650 QualType ToType,
2651 CXXConversionDecl *&Specialization,
2652 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002654 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2655 QualType FromType = Conv->getConversionType();
2656
2657 // Canonicalize the types for deduction.
2658 QualType P = Context.getCanonicalType(FromType);
2659 QualType A = Context.getCanonicalType(ToType);
2660
2661 // C++0x [temp.deduct.conv]p3:
2662 // If P is a reference type, the type referred to by P is used for
2663 // type deduction.
2664 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2665 P = PRef->getPointeeType();
2666
2667 // C++0x [temp.deduct.conv]p3:
2668 // If A is a reference type, the type referred to by A is used
2669 // for type deduction.
2670 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2671 A = ARef->getPointeeType();
2672 // C++ [temp.deduct.conv]p2:
2673 //
Mike Stump1eb44332009-09-09 15:08:12 +00002674 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002675 else {
2676 assert(!A->isReferenceType() && "Reference types were handled above");
2677
2678 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002679 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002680 // of P for type deduction; otherwise,
2681 if (P->isArrayType())
2682 P = Context.getArrayDecayedType(P);
2683 // - If P is a function type, the pointer type produced by the
2684 // function-to-pointer standard conversion (4.3) is used in
2685 // place of P for type deduction; otherwise,
2686 else if (P->isFunctionType())
2687 P = Context.getPointerType(P);
2688 // - If P is a cv-qualified type, the top level cv-qualifiers of
2689 // P’s type are ignored for type deduction.
2690 else
2691 P = P.getUnqualifiedType();
2692
2693 // C++0x [temp.deduct.conv]p3:
2694 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2695 // type are ignored for type deduction.
2696 A = A.getUnqualifiedType();
2697 }
2698
2699 // Template argument deduction for function templates in a SFINAE context.
2700 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002701 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002702
2703 // C++ [temp.deduct.conv]p1:
2704 // Template argument deduction is done by comparing the return
2705 // type of the template conversion function (call it P) with the
2706 // type that is required as the result of the conversion (call it
2707 // A) as described in 14.8.2.4.
2708 TemplateParameterList *TemplateParams
2709 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002710 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002711 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002712
2713 // C++0x [temp.deduct.conv]p4:
2714 // In general, the deduction process attempts to find template
2715 // argument values that will make the deduced A identical to
2716 // A. However, there are two cases that allow a difference:
2717 unsigned TDF = 0;
2718 // - If the original A is a reference type, A can be more
2719 // cv-qualified than the deduced A (i.e., the type referred to
2720 // by the reference)
2721 if (ToType->isReferenceType())
2722 TDF |= TDF_ParamWithReferenceType;
2723 // - The deduced A can be another pointer or pointer to member
2724 // type that can be converted to A via a qualification
2725 // conversion.
2726 //
2727 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2728 // both P and A are pointers or member pointers. In this case, we
2729 // just ignore cv-qualifiers completely).
2730 if ((P->isPointerType() && A->isPointerType()) ||
2731 (P->isMemberPointerType() && P->isMemberPointerType()))
2732 TDF |= TDF_IgnoreQualifiers;
2733 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002734 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002735 P, A, Info, Deduced, TDF))
2736 return Result;
2737
2738 // FIXME: we need to check that the deduced A is the same as A,
2739 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002741 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002742 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002743 FunctionDecl *Spec = 0;
2744 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002745 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2746 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002747 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2748 return Result;
2749}
2750
Douglas Gregor4b52e252009-12-21 23:17:24 +00002751/// \brief Deduce template arguments for a function template when there is
2752/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2753///
2754/// \param FunctionTemplate the function template for which we are performing
2755/// template argument deduction.
2756///
2757/// \param ExplicitTemplateArguments the explicitly-specified template
2758/// arguments.
2759///
2760/// \param Specialization if template argument deduction was successful,
2761/// this will be set to the function template specialization produced by
2762/// template argument deduction.
2763///
2764/// \param Info the argument will be updated to provide additional information
2765/// about template argument deduction.
2766///
2767/// \returns the result of template argument deduction.
2768Sema::TemplateDeductionResult
2769Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2770 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2771 FunctionDecl *&Specialization,
2772 TemplateDeductionInfo &Info) {
2773 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2774 QualType(), Specialization, Info);
2775}
2776
Douglas Gregor8a514912009-09-14 18:39:43 +00002777/// \brief Stores the result of comparing the qualifiers of two types.
2778enum DeductionQualifierComparison {
2779 NeitherMoreQualified = 0,
2780 ParamMoreQualified,
2781 ArgMoreQualified
2782};
2783
2784/// \brief Deduce the template arguments during partial ordering by comparing
2785/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2786///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002787/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002788///
2789/// \param TemplateParams the template parameters that we are deducing
2790///
2791/// \param ParamIn the parameter type
2792///
2793/// \param ArgIn the argument type
2794///
2795/// \param Info information about the template argument deduction itself
2796///
2797/// \param Deduced the deduced template arguments
2798///
2799/// \returns the result of template argument deduction so far. Note that a
2800/// "success" result means that template argument deduction has not yet failed,
2801/// but it may still fail, later, for other reasons.
2802static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002803DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002804 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002805 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002806 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002807 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2808 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002809 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2810 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002811
2812 // C++0x [temp.deduct.partial]p5:
2813 // Before the partial ordering is done, certain transformations are
2814 // performed on the types used for partial ordering:
2815 // - If P is a reference type, P is replaced by the type referred to.
2816 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002817 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002818 Param = ParamRef->getPointeeType();
2819
2820 // - If A is a reference type, A is replaced by the type referred to.
2821 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002822 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002823 Arg = ArgRef->getPointeeType();
2824
John McCalle27ec8a2009-10-23 23:03:21 +00002825 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002826 // C++0x [temp.deduct.partial]p6:
2827 // If both P and A were reference types (before being replaced with the
2828 // type referred to above), determine which of the two types (if any) is
2829 // more cv-qualified than the other; otherwise the types are considered to
2830 // be equally cv-qualified for partial ordering purposes. The result of this
2831 // determination will be used below.
2832 //
2833 // We save this information for later, using it only when deduction
2834 // succeeds in both directions.
2835 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2836 if (Param.isMoreQualifiedThan(Arg))
2837 QualifierResult = ParamMoreQualified;
2838 else if (Arg.isMoreQualifiedThan(Param))
2839 QualifierResult = ArgMoreQualified;
2840 QualifierComparisons->push_back(QualifierResult);
2841 }
2842
2843 // C++0x [temp.deduct.partial]p7:
2844 // Remove any top-level cv-qualifiers:
2845 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2846 // version of P.
2847 Param = Param.getUnqualifiedType();
2848 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2849 // version of A.
2850 Arg = Arg.getUnqualifiedType();
2851
2852 // C++0x [temp.deduct.partial]p8:
2853 // Using the resulting types P and A the deduction is then done as
2854 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2855 // from the argument template is considered to be at least as specialized
2856 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002857 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002858 Deduced, TDF_None);
2859}
2860
2861static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002862MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2863 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002864 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002865 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002866
2867/// \brief If this is a non-static member function,
2868static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2869 CXXMethodDecl *Method,
2870 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2871 if (Method->isStatic())
2872 return;
2873
2874 // C++ [over.match.funcs]p4:
2875 //
2876 // For non-static member functions, the type of the implicit
2877 // object parameter is
2878 // — "lvalue reference to cv X" for functions declared without a
2879 // ref-qualifier or with the & ref-qualifier
2880 // - "rvalue reference to cv X" for functions declared with the
2881 // && ref-qualifier
2882 //
2883 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2884 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2885 ArgTy = Context.getQualifiedType(ArgTy,
2886 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2887 ArgTy = Context.getLValueReferenceType(ArgTy);
2888 ArgTypes.push_back(ArgTy);
2889}
2890
Douglas Gregor8a514912009-09-14 18:39:43 +00002891/// \brief Determine whether the function template \p FT1 is at least as
2892/// specialized as \p FT2.
2893static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002894 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002895 FunctionTemplateDecl *FT1,
2896 FunctionTemplateDecl *FT2,
2897 TemplatePartialOrderingContext TPOC,
2898 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2899 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2900 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2901 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2902 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2903
2904 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2905 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002906 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002907 Deduced.resize(TemplateParams->size());
2908
2909 // C++0x [temp.deduct.partial]p3:
2910 // The types used to determine the ordering depend on the context in which
2911 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002912 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002913 CXXMethodDecl *Method1 = 0;
2914 CXXMethodDecl *Method2 = 0;
2915 bool IsNonStatic2 = false;
2916 bool IsNonStatic1 = false;
2917 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002918 switch (TPOC) {
2919 case TPOC_Call: {
2920 // - In the context of a function call, the function parameter types are
2921 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002922 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2923 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2924 IsNonStatic1 = Method1 && !Method1->isStatic();
2925 IsNonStatic2 = Method2 && !Method2->isStatic();
2926
2927 // C++0x [temp.func.order]p3:
2928 // [...] If only one of the function templates is a non-static
2929 // member, that function template is considered to have a new
2930 // first parameter inserted in its function parameter list. The
2931 // new parameter is of type "reference to cv A," where cv are
2932 // the cv-qualifiers of the function template (if any) and A is
2933 // the class of which the function template is a member.
2934 //
2935 // C++98/03 doesn't have this provision, so instead we drop the
2936 // first argument of the free function or static member, which
2937 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002938 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002939 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2940 IsNonStatic2 && !IsNonStatic1;
2941 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002942 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2943 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002944 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002945
2946 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002947 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2948 IsNonStatic1 && !IsNonStatic2;
2949 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002950 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2951 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002952 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002953
2954 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002955 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002956 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002957 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002958 Args2[I],
2959 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002960 Info,
2961 Deduced,
2962 QualifierComparisons))
2963 return false;
2964
2965 break;
2966 }
2967
2968 case TPOC_Conversion:
2969 // - In the context of a call to a conversion operator, the return types
2970 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002971 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002972 TemplateParams,
2973 Proto2->getResultType(),
2974 Proto1->getResultType(),
2975 Info,
2976 Deduced,
2977 QualifierComparisons))
2978 return false;
2979 break;
2980
2981 case TPOC_Other:
2982 // - In other contexts (14.6.6.2) the function template’s function type
2983 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002984 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002985 TemplateParams,
2986 FD2->getType(),
2987 FD1->getType(),
2988 Info,
2989 Deduced,
2990 QualifierComparisons))
2991 return false;
2992 break;
2993 }
2994
2995 // C++0x [temp.deduct.partial]p11:
2996 // In most cases, all template parameters must have values in order for
2997 // deduction to succeed, but for partial ordering purposes a template
2998 // parameter may remain without a value provided it is not used in the
2999 // types being used for partial ordering. [ Note: a template parameter used
3000 // in a non-deduced context is considered used. -end note]
3001 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3002 for (; ArgIdx != NumArgs; ++ArgIdx)
3003 if (Deduced[ArgIdx].isNull())
3004 break;
3005
3006 if (ArgIdx == NumArgs) {
3007 // All template arguments were deduced. FT1 is at least as specialized
3008 // as FT2.
3009 return true;
3010 }
3011
Douglas Gregore73bb602009-09-14 21:25:05 +00003012 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003013 llvm::SmallVector<bool, 4> UsedParameters;
3014 UsedParameters.resize(TemplateParams->size());
3015 switch (TPOC) {
3016 case TPOC_Call: {
3017 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003018 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3019 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3020 TemplateParams->getDepth(), UsedParameters);
3021 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003022 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3023 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003024 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003025 break;
3026 }
3027
3028 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003029 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3030 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003031 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003032 break;
3033
3034 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003035 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3036 TemplateParams->getDepth(),
3037 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003038 break;
3039 }
3040
3041 for (; ArgIdx != NumArgs; ++ArgIdx)
3042 // If this argument had no value deduced but was used in one of the types
3043 // used for partial ordering, then deduction fails.
3044 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3045 return false;
3046
3047 return true;
3048}
3049
3050
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003051/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003052/// to the rules of function template partial ordering (C++ [temp.func.order]).
3053///
3054/// \param FT1 the first function template
3055///
3056/// \param FT2 the second function template
3057///
Douglas Gregor8a514912009-09-14 18:39:43 +00003058/// \param TPOC the context in which we are performing partial ordering of
3059/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003060///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003061/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003062/// template is more specialized, returns NULL.
3063FunctionTemplateDecl *
3064Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3065 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003066 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003067 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003068 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003069 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3070 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003071 &QualifierComparisons);
3072
3073 if (Better1 != Better2) // We have a clear winner
3074 return Better1? FT1 : FT2;
3075
3076 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003077 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003078
3079
3080 // C++0x [temp.deduct.partial]p10:
3081 // If for each type being considered a given template is at least as
3082 // specialized for all types and more specialized for some set of types and
3083 // the other template is not more specialized for any types or is not at
3084 // least as specialized for any types, then the given template is more
3085 // specialized than the other template. Otherwise, neither template is more
3086 // specialized than the other.
3087 Better1 = false;
3088 Better2 = false;
3089 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3090 // C++0x [temp.deduct.partial]p9:
3091 // If, for a given type, deduction succeeds in both directions (i.e., the
3092 // types are identical after the transformations above) and if the type
3093 // from the argument template is more cv-qualified than the type from the
3094 // parameter template (as described above) that type is considered to be
3095 // more specialized than the other. If neither type is more cv-qualified
3096 // than the other then neither type is more specialized than the other.
3097 switch (QualifierComparisons[I]) {
3098 case NeitherMoreQualified:
3099 break;
3100
3101 case ParamMoreQualified:
3102 Better1 = true;
3103 if (Better2)
3104 return 0;
3105 break;
3106
3107 case ArgMoreQualified:
3108 Better2 = true;
3109 if (Better1)
3110 return 0;
3111 break;
3112 }
3113 }
3114
3115 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003116 if (Better1)
3117 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003118 else if (Better2)
3119 return FT2;
3120 else
3121 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003122}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003123
Douglas Gregord5a423b2009-09-25 18:43:00 +00003124/// \brief Determine if the two templates are equivalent.
3125static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3126 if (T1 == T2)
3127 return true;
3128
3129 if (!T1 || !T2)
3130 return false;
3131
3132 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3133}
3134
3135/// \brief Retrieve the most specialized of the given function template
3136/// specializations.
3137///
John McCallc373d482010-01-27 01:50:18 +00003138/// \param SpecBegin the start iterator of the function template
3139/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003140///
John McCallc373d482010-01-27 01:50:18 +00003141/// \param SpecEnd the end iterator of the function template
3142/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003143///
3144/// \param TPOC the partial ordering context to use to compare the function
3145/// template specializations.
3146///
3147/// \param Loc the location where the ambiguity or no-specializations
3148/// diagnostic should occur.
3149///
3150/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3151/// no matching candidates.
3152///
3153/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3154/// occurs.
3155///
3156/// \param CandidateDiag partial diagnostic used for each function template
3157/// specialization that is a candidate in the ambiguous ordering. One parameter
3158/// in this diagnostic should be unbound, which will correspond to the string
3159/// describing the template arguments for the function template specialization.
3160///
3161/// \param Index if non-NULL and the result of this function is non-nULL,
3162/// receives the index corresponding to the resulting function template
3163/// specialization.
3164///
3165/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003166/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003167///
3168/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3169/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003170UnresolvedSetIterator
3171Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3172 UnresolvedSetIterator SpecEnd,
3173 TemplatePartialOrderingContext TPOC,
3174 SourceLocation Loc,
3175 const PartialDiagnostic &NoneDiag,
3176 const PartialDiagnostic &AmbigDiag,
3177 const PartialDiagnostic &CandidateDiag) {
3178 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003179 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003180 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003181 }
3182
John McCallc373d482010-01-27 01:50:18 +00003183 if (SpecBegin + 1 == SpecEnd)
3184 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003185
3186 // Find the function template that is better than all of the templates it
3187 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003188 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003189 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003190 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003191 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003192 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3193 FunctionTemplateDecl *Challenger
3194 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003195 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003196 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003197 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003198 Challenger)) {
3199 Best = I;
3200 BestTemplate = Challenger;
3201 }
3202 }
3203
3204 // Make sure that the "best" function template is more specialized than all
3205 // of the others.
3206 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003207 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3208 FunctionTemplateDecl *Challenger
3209 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003210 if (I != Best &&
3211 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003212 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003213 BestTemplate)) {
3214 Ambiguous = true;
3215 break;
3216 }
3217 }
3218
3219 if (!Ambiguous) {
3220 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003221 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003222 }
3223
3224 // Diagnose the ambiguity.
3225 Diag(Loc, AmbigDiag);
3226
3227 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003228 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3229 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003230 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003231 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3232 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003233
John McCallc373d482010-01-27 01:50:18 +00003234 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003235}
3236
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003237/// \brief Returns the more specialized class template partial specialization
3238/// according to the rules of partial ordering of class template partial
3239/// specializations (C++ [temp.class.order]).
3240///
3241/// \param PS1 the first class template partial specialization
3242///
3243/// \param PS2 the second class template partial specialization
3244///
3245/// \returns the more specialized class template partial specialization. If
3246/// neither partial specialization is more specialized, returns NULL.
3247ClassTemplatePartialSpecializationDecl *
3248Sema::getMoreSpecializedPartialSpecialization(
3249 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003250 ClassTemplatePartialSpecializationDecl *PS2,
3251 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003252 // C++ [temp.class.order]p1:
3253 // For two class template partial specializations, the first is at least as
3254 // specialized as the second if, given the following rewrite to two
3255 // function templates, the first function template is at least as
3256 // specialized as the second according to the ordering rules for function
3257 // templates (14.6.6.2):
3258 // - the first function template has the same template parameters as the
3259 // first partial specialization and has a single function parameter
3260 // whose type is a class template specialization with the template
3261 // arguments of the first partial specialization, and
3262 // - the second function template has the same template parameters as the
3263 // second partial specialization and has a single function parameter
3264 // whose type is a class template specialization with the template
3265 // arguments of the second partial specialization.
3266 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003267 // Rather than synthesize function templates, we merely perform the
3268 // equivalent partial ordering by performing deduction directly on
3269 // the template arguments of the class template partial
3270 // specializations. This computation is slightly simpler than the
3271 // general problem of function template partial ordering, because
3272 // class template partial specializations are more constrained. We
3273 // know that every template parameter is deducible from the class
3274 // template partial specialization's template arguments, for
3275 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003276 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003277 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003278
3279 QualType PT1 = PS1->getInjectedSpecializationType();
3280 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003281
3282 // Determine whether PS1 is at least as specialized as PS2
3283 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003284 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003285 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003286 PT2,
3287 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003288 Info,
3289 Deduced,
3290 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003291 if (Better1) {
3292 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3293 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003294 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3295 PS1->getTemplateArgs(),
3296 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003297 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003298
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003299 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003300 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003301 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003302 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003303 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003304 PT1,
3305 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003306 Info,
3307 Deduced,
3308 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003309 if (Better2) {
3310 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3311 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003312 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3313 PS2->getTemplateArgs(),
3314 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003315 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003316
3317 if (Better1 == Better2)
3318 return 0;
3319
3320 return Better1? PS1 : PS2;
3321}
3322
Mike Stump1eb44332009-09-09 15:08:12 +00003323static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003324MarkUsedTemplateParameters(Sema &SemaRef,
3325 const TemplateArgument &TemplateArg,
3326 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003327 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003328 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003329
Douglas Gregore73bb602009-09-14 21:25:05 +00003330/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003331/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003332static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003333MarkUsedTemplateParameters(Sema &SemaRef,
3334 const Expr *E,
3335 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003336 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003337 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003338 // We can deduce from a pack expansion.
3339 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3340 E = Expansion->getPattern();
3341
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003342 // Skip through any implicit casts we added while type-checking.
3343 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3344 E = ICE->getSubExpr();
3345
Douglas Gregore73bb602009-09-14 21:25:05 +00003346 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3347 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003348 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003349 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003350 return;
3351
Mike Stump1eb44332009-09-09 15:08:12 +00003352 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003353 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3354 if (!NTTP)
3355 return;
3356
Douglas Gregored9c0f92009-10-29 00:04:11 +00003357 if (NTTP->getDepth() == Depth)
3358 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003359}
3360
Douglas Gregore73bb602009-09-14 21:25:05 +00003361/// \brief Mark the template parameters that are used by the given
3362/// nested name specifier.
3363static void
3364MarkUsedTemplateParameters(Sema &SemaRef,
3365 NestedNameSpecifier *NNS,
3366 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003367 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003368 llvm::SmallVectorImpl<bool> &Used) {
3369 if (!NNS)
3370 return;
3371
Douglas Gregored9c0f92009-10-29 00:04:11 +00003372 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3373 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003374 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003375 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003376}
3377
3378/// \brief Mark the template parameters that are used by the given
3379/// template name.
3380static void
3381MarkUsedTemplateParameters(Sema &SemaRef,
3382 TemplateName Name,
3383 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003384 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003385 llvm::SmallVectorImpl<bool> &Used) {
3386 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3387 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003388 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3389 if (TTP->getDepth() == Depth)
3390 Used[TTP->getIndex()] = true;
3391 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003392 return;
3393 }
3394
Douglas Gregor788cd062009-11-11 01:00:40 +00003395 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3396 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3397 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003398 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003399 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3400 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003401}
3402
3403/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003404/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003405static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003406MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3407 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003408 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003409 llvm::SmallVectorImpl<bool> &Used) {
3410 if (T.isNull())
3411 return;
3412
Douglas Gregor031a5882009-06-13 00:26:55 +00003413 // Non-dependent types have nothing deducible
3414 if (!T->isDependentType())
3415 return;
3416
3417 T = SemaRef.Context.getCanonicalType(T);
3418 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003419 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003420 MarkUsedTemplateParameters(SemaRef,
3421 cast<PointerType>(T)->getPointeeType(),
3422 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003423 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003424 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003425 break;
3426
3427 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003428 MarkUsedTemplateParameters(SemaRef,
3429 cast<BlockPointerType>(T)->getPointeeType(),
3430 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003431 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003432 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003433 break;
3434
3435 case Type::LValueReference:
3436 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003437 MarkUsedTemplateParameters(SemaRef,
3438 cast<ReferenceType>(T)->getPointeeType(),
3439 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003440 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003441 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003442 break;
3443
3444 case Type::MemberPointer: {
3445 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003446 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003447 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003448 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003449 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003450 break;
3451 }
3452
3453 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003454 MarkUsedTemplateParameters(SemaRef,
3455 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003456 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003457 // Fall through to check the element type
3458
3459 case Type::ConstantArray:
3460 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003461 MarkUsedTemplateParameters(SemaRef,
3462 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003463 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003464 break;
3465
3466 case Type::Vector:
3467 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003468 MarkUsedTemplateParameters(SemaRef,
3469 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003470 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003471 break;
3472
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003473 case Type::DependentSizedExtVector: {
3474 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003475 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003476 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003477 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003478 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003479 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003480 break;
3481 }
3482
Douglas Gregor031a5882009-06-13 00:26:55 +00003483 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003484 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003485 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003486 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003487 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003489 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003490 break;
3491 }
3492
Douglas Gregored9c0f92009-10-29 00:04:11 +00003493 case Type::TemplateTypeParm: {
3494 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3495 if (TTP->getDepth() == Depth)
3496 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003497 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003499
John McCall31f17ec2010-04-27 00:57:59 +00003500 case Type::InjectedClassName:
3501 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3502 // fall through
3503
Douglas Gregor031a5882009-06-13 00:26:55 +00003504 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003505 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003506 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003507 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003508 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003509
3510 // C++0x [temp.deduct.type]p9:
3511 // If the template argument list of P contains a pack expansion that is not
3512 // the last template argument, the entire template argument list is a
3513 // non-deduced context.
3514 if (OnlyDeduced &&
3515 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3516 break;
3517
Douglas Gregore73bb602009-09-14 21:25:05 +00003518 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003519 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3520 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003521 break;
3522 }
3523
Douglas Gregore73bb602009-09-14 21:25:05 +00003524 case Type::Complex:
3525 if (!OnlyDeduced)
3526 MarkUsedTemplateParameters(SemaRef,
3527 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003528 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003529 break;
3530
Douglas Gregor4714c122010-03-31 17:34:00 +00003531 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003532 if (!OnlyDeduced)
3533 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003534 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003535 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003536 break;
3537
John McCall33500952010-06-11 00:33:02 +00003538 case Type::DependentTemplateSpecialization: {
3539 const DependentTemplateSpecializationType *Spec
3540 = cast<DependentTemplateSpecializationType>(T);
3541 if (!OnlyDeduced)
3542 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3543 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003544
3545 // C++0x [temp.deduct.type]p9:
3546 // If the template argument list of P contains a pack expansion that is not
3547 // the last template argument, the entire template argument list is a
3548 // non-deduced context.
3549 if (OnlyDeduced &&
3550 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3551 break;
3552
John McCall33500952010-06-11 00:33:02 +00003553 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3554 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3555 Used);
3556 break;
3557 }
3558
John McCallad5e7382010-03-01 23:49:17 +00003559 case Type::TypeOf:
3560 if (!OnlyDeduced)
3561 MarkUsedTemplateParameters(SemaRef,
3562 cast<TypeOfType>(T)->getUnderlyingType(),
3563 OnlyDeduced, Depth, Used);
3564 break;
3565
3566 case Type::TypeOfExpr:
3567 if (!OnlyDeduced)
3568 MarkUsedTemplateParameters(SemaRef,
3569 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3570 OnlyDeduced, Depth, Used);
3571 break;
3572
3573 case Type::Decltype:
3574 if (!OnlyDeduced)
3575 MarkUsedTemplateParameters(SemaRef,
3576 cast<DecltypeType>(T)->getUnderlyingExpr(),
3577 OnlyDeduced, Depth, Used);
3578 break;
3579
Douglas Gregor7536dd52010-12-20 02:24:11 +00003580 case Type::PackExpansion:
3581 MarkUsedTemplateParameters(SemaRef,
3582 cast<PackExpansionType>(T)->getPattern(),
3583 OnlyDeduced, Depth, Used);
3584 break;
3585
Douglas Gregore73bb602009-09-14 21:25:05 +00003586 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003587 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003588 case Type::VariableArray:
3589 case Type::FunctionNoProto:
3590 case Type::Record:
3591 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003592 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003593 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003594 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003595 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003596#define TYPE(Class, Base)
3597#define ABSTRACT_TYPE(Class, Base)
3598#define DEPENDENT_TYPE(Class, Base)
3599#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3600#include "clang/AST/TypeNodes.def"
3601 break;
3602 }
3603}
3604
Douglas Gregore73bb602009-09-14 21:25:05 +00003605/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003606/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003607static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003608MarkUsedTemplateParameters(Sema &SemaRef,
3609 const TemplateArgument &TemplateArg,
3610 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003611 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003612 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003613 switch (TemplateArg.getKind()) {
3614 case TemplateArgument::Null:
3615 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003616 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003617 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Douglas Gregor031a5882009-06-13 00:26:55 +00003619 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003620 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003621 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003622 break;
3623
Douglas Gregor788cd062009-11-11 01:00:40 +00003624 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003625 case TemplateArgument::TemplateExpansion:
3626 MarkUsedTemplateParameters(SemaRef,
3627 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003628 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003629 break;
3630
3631 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003632 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003633 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003634 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003635
Anders Carlssond01b1da2009-06-15 17:04:53 +00003636 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003637 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3638 PEnd = TemplateArg.pack_end();
3639 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003640 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003641 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003642 }
3643}
3644
3645/// \brief Mark the template parameters can be deduced by the given
3646/// template argument list.
3647///
3648/// \param TemplateArgs the template argument list from which template
3649/// parameters will be deduced.
3650///
3651/// \param Deduced a bit vector whose elements will be set to \c true
3652/// to indicate when the corresponding template parameter will be
3653/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003654void
Douglas Gregore73bb602009-09-14 21:25:05 +00003655Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003656 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003657 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003658 // C++0x [temp.deduct.type]p9:
3659 // If the template argument list of P contains a pack expansion that is not
3660 // the last template argument, the entire template argument list is a
3661 // non-deduced context.
3662 if (OnlyDeduced &&
3663 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3664 return;
3665
Douglas Gregor031a5882009-06-13 00:26:55 +00003666 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003667 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3668 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003669}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003670
3671/// \brief Marks all of the template parameters that will be deduced by a
3672/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003673void
3674Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3675 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003676 TemplateParameterList *TemplateParams
3677 = FunctionTemplate->getTemplateParameters();
3678 Deduced.clear();
3679 Deduced.resize(TemplateParams->size());
3680
3681 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3682 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3683 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003684 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003685}