blob: 02e1a42dc3965d3917e4a48e4bd25fbcf17cc276 [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])))
639 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
640 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000641
642 // C++0x [temp.deduct.type]p10:
643 // Similarly, if P has a form that contains (T), then each parameter type
644 // Pi of the respective parameter-type- list of P is compared with the
645 // corresponding parameter type Ai of the corresponding parameter-type-list
646 // of A. [...]
647 unsigned ArgIdx = 0, ParamIdx = 0;
648 for (; ParamIdx != NumParams; ++ParamIdx) {
649 // Check argument types.
650 const PackExpansionType *Expansion
651 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
652 if (!Expansion) {
653 // Simple case: compare the parameter and argument types at this point.
654
655 // Make sure we have an argument.
656 if (ArgIdx >= NumArgs)
657 return Sema::TDK_TooFewArguments;
658
659 if (Sema::TemplateDeductionResult Result
660 = DeduceTemplateArguments(S, TemplateParams,
661 Params[ParamIdx],
662 Args[ArgIdx],
663 Info, Deduced, TDF))
664 return Result;
665
666 ++ArgIdx;
667 continue;
668 }
669
670 // C++0x [temp.deduct.type]p10:
671 // If the parameter-declaration corresponding to Pi is a function
672 // parameter pack, then the type of its declarator- id is compared with
673 // each remaining parameter type in the parameter-type-list of A. Each
674 // comparison deduces template arguments for subsequent positions in the
675 // template parameter packs expanded by the function parameter pack.
676
677 // Compute the set of template parameter indices that correspond to
678 // parameter packs expanded by the pack expansion.
679 llvm::SmallVector<unsigned, 2> PackIndices;
680 QualType Pattern = Expansion->getPattern();
681 {
682 llvm::BitVector SawIndices(TemplateParams->size());
683 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
684 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
685 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
686 unsigned Depth, Index;
687 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
688 if (Depth == 0 && !SawIndices[Index]) {
689 SawIndices[Index] = true;
690 PackIndices.push_back(Index);
691 }
692 }
693 }
694 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
695
Douglas Gregord3731192011-01-10 07:32:04 +0000696 // Keep track of the deduced template arguments for each parameter pack
697 // expanded by this pack expansion (the outer index) and for each
698 // template argument (the inner SmallVectors).
699 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
700 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000701 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000702 SavedPacks(PackIndices.size());
703 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
704 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000705
Douglas Gregor603cfb42011-01-05 23:12:31 +0000706 bool HasAnyArguments = false;
707 for (; ArgIdx < NumArgs; ++ArgIdx) {
708 HasAnyArguments = true;
709
710 // Deduce template arguments from the pattern.
711 if (Sema::TemplateDeductionResult Result
712 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
713 Info, Deduced))
714 return Result;
715
716 // Capture the deduced template arguments for each parameter pack expanded
717 // by this pack expansion, add them to the list of arguments we've deduced
718 // for that pack, then clear out the deduced argument.
719 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
720 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
721 if (!DeducedArg.isNull()) {
722 NewlyDeducedPacks[I].push_back(DeducedArg);
723 DeducedArg = DeducedTemplateArgument();
724 }
725 }
726 }
727
728 // Build argument packs for each of the parameter packs expanded by this
729 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000730 if (Sema::TemplateDeductionResult Result
731 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
732 Deduced, PackIndices, SavedPacks,
733 NewlyDeducedPacks, Info))
734 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000735 }
736
737 // Make sure we don't have any extra arguments.
738 if (ArgIdx < NumArgs)
739 return Sema::TDK_TooManyArguments;
740
741 return Sema::TDK_Success;
742}
743
Douglas Gregor500d3312009-06-26 18:27:22 +0000744/// \brief Deduce the template arguments by comparing the parameter type and
745/// the argument type (C++ [temp.deduct.type]).
746///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000747/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000748///
749/// \param TemplateParams the template parameters that we are deducing
750///
751/// \param ParamIn the parameter type
752///
753/// \param ArgIn the argument type
754///
755/// \param Info information about the template argument deduction itself
756///
757/// \param Deduced the deduced template arguments
758///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000759/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000760/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000761///
762/// \returns the result of template argument deduction so far. Note that a
763/// "success" result means that template argument deduction has not yet failed,
764/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000765static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000766DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000767 TemplateParameterList *TemplateParams,
768 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000769 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000770 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000771 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000772 // We only want to look at the canonical types, since typedefs and
773 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000774 QualType Param = S.Context.getCanonicalType(ParamIn);
775 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000776
Douglas Gregor500d3312009-06-26 18:27:22 +0000777 // C++0x [temp.deduct.call]p4 bullet 1:
778 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000779 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000780 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000781 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000782 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000783 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000784 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
785 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000786 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000789 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000790 if (!Param->isDependentType()) {
791 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
792
793 return Sema::TDK_NonDeducedMismatch;
794 }
795
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000796 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000797 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000798
Douglas Gregor199d9912009-06-05 00:53:49 +0000799 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000800 // A template type argument T, a template template argument TT or a
801 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000802 // the following forms:
803 //
804 // T
805 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000806 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000807 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000808 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000809 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000811 // If the argument type is an array type, move the qualifiers up to the
812 // top level, so they can be matched with the qualifiers on the parameter.
813 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000814 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000815 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000816 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000817 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000818 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000819 RecanonicalizeArg = true;
820 }
821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000823 // The argument type can not be less qualified than the parameter
824 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000825 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000826 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000827 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000828 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000829 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000830 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000831
832 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000833 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000834 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000835
836 // local manipulation is okay because it's canonical
837 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000838 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000839 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000841 DeducedTemplateArgument NewDeduced(DeducedType);
842 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
843 Deduced[Index],
844 NewDeduced);
845 if (Result.isNull()) {
846 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
847 Info.FirstArg = Deduced[Index];
848 Info.SecondArg = NewDeduced;
849 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000850 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000851
852 Deduced[Index] = Result;
853 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000854 }
855
Douglas Gregorf67875d2009-06-12 18:26:56 +0000856 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000857 Info.FirstArg = TemplateArgument(ParamIn);
858 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000859
Douglas Gregor508f1c82009-06-26 23:10:12 +0000860 // Check the cv-qualifiers on the parameter and argument types.
861 if (!(TDF & TDF_IgnoreQualifiers)) {
862 if (TDF & TDF_ParamWithReferenceType) {
863 if (Param.isMoreQualifiedThan(Arg))
864 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000865 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000866 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000867 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000868 }
869 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000870
Douglas Gregord560d502009-06-04 00:21:18 +0000871 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000872 // No deduction possible for these types
873 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000874 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Douglas Gregor199d9912009-06-05 00:53:49 +0000876 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000877 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000878 QualType PointeeType;
879 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
880 PointeeType = PointerArg->getPointeeType();
881 } else if (const ObjCObjectPointerType *PointerArg
882 = Arg->getAs<ObjCObjectPointerType>()) {
883 PointeeType = PointerArg->getPointeeType();
884 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000885 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregor41128772009-06-26 23:27:24 +0000888 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000889 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000890 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000891 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000892 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000896 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000897 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000898 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000899 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000901 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000902 cast<LValueReferenceType>(Param)->getPointeeType(),
903 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000904 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000905 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000906
Douglas Gregor199d9912009-06-05 00:53:49 +0000907 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000908 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000909 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000910 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000911 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000913 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000914 cast<RValueReferenceType>(Param)->getPointeeType(),
915 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000916 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Douglas Gregor199d9912009-06-05 00:53:49 +0000919 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000920 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000921 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000922 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000923 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000924 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
John McCalle4f26e52010-08-19 00:20:19 +0000926 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000927 return DeduceTemplateArguments(S, TemplateParams,
928 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000929 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000930 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000931 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000932
933 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000934 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000935 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000936 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000937 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000938 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000939
940 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000941 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000942 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000943 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000944
John McCalle4f26e52010-08-19 00:20:19 +0000945 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000946 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000947 ConstantArrayParm->getElementType(),
948 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000949 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000950 }
951
Douglas Gregor199d9912009-06-05 00:53:49 +0000952 // type [i]
953 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000954 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000955 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000956 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
John McCalle4f26e52010-08-19 00:20:19 +0000958 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
959
Douglas Gregor199d9912009-06-05 00:53:49 +0000960 // Check the element type of the arrays
961 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000962 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000963 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000964 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965 DependentArrayParm->getElementType(),
966 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000967 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor199d9912009-06-05 00:53:49 +0000970 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000971 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000972 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
973 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000974 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000975
976 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000977 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000978 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000979 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000980 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000981 = dyn_cast<ConstantArrayType>(ArrayArg)) {
982 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000983 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
984 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000985 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000986 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000987 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000988 if (const DependentSizedArrayType *DependentArrayArg
989 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000990 if (DependentArrayArg->getSizeExpr())
991 return DeduceNonTypeTemplateArgument(S, NTTP,
992 DependentArrayArg->getSizeExpr(),
993 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Douglas Gregor199d9912009-06-05 00:53:49 +0000995 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000996 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
999 // type(*)(T)
1000 // T(*)()
1001 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001002 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001003 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001004 dyn_cast<FunctionProtoType>(Arg);
1005 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001006 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
1008 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001009 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001010
Mike Stump1eb44332009-09-09 15:08:12 +00001011 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001012 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001013 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001015 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001016 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001017
Anders Carlssona27fad52009-06-08 15:19:08 +00001018 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001019 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001020 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001021 FunctionProtoParam->getResultType(),
1022 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001023 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001024 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Douglas Gregor603cfb42011-01-05 23:12:31 +00001026 return DeduceTemplateArguments(S, TemplateParams,
1027 FunctionProtoParam->arg_type_begin(),
1028 FunctionProtoParam->getNumArgs(),
1029 FunctionProtoArg->arg_type_begin(),
1030 FunctionProtoArg->getNumArgs(),
1031 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
John McCall3cb0ebd2010-03-10 03:28:59 +00001034 case Type::InjectedClassName: {
1035 // Treat a template's injected-class-name as if the template
1036 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001037 Param = cast<InjectedClassNameType>(Param)
1038 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001039 assert(isa<TemplateSpecializationType>(Param) &&
1040 "injected class name is not a template specialization type");
1041 // fall through
1042 }
1043
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001044 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001045 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001046 // TT<T>
1047 // TT<i>
1048 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001049 case Type::TemplateSpecialization: {
1050 const TemplateSpecializationType *SpecParam
1051 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001053 // Try to deduce template arguments from the template-id.
1054 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001055 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001056 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001058 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001059 // C++ [temp.deduct.call]p3b3:
1060 // If P is a class, and P has the form template-id, then A can be a
1061 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001062 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001063 // class pointed to by the deduced A.
1064 //
1065 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001066 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001067 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001068 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1069 // We cannot inspect base classes as part of deduction when the type
1070 // is incomplete, so either instantiate any templates necessary to
1071 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001072 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001073 return Result;
1074
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001075 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001076 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001077 // ToVisit is our stack of records that we still need to visit.
1078 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1079 llvm::SmallVector<const RecordType *, 8> ToVisit;
1080 ToVisit.push_back(RecordT);
1081 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001082 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1083 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001084 while (!ToVisit.empty()) {
1085 // Retrieve the next class in the inheritance hierarchy.
1086 const RecordType *NextT = ToVisit.back();
1087 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001089 // If we have already seen this type, skip it.
1090 if (!Visited.insert(NextT))
1091 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001093 // If this is a base class, try to perform template argument
1094 // deduction from it.
1095 if (NextT != RecordT) {
1096 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001097 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001098 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001100 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001101 // note that we had some success. Otherwise, ignore any deductions
1102 // from this base class.
1103 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001104 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001105 DeducedOrig = Deduced;
1106 }
1107 else
1108 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001111 // Visit base classes
1112 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1113 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1114 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001115 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001116 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001117 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001118 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001119 }
1120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001122 if (Successful)
1123 return Sema::TDK_Success;
1124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001128 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001129 }
1130
Douglas Gregor637a4092009-06-10 23:47:09 +00001131 // T type::*
1132 // T T::*
1133 // T (type::*)()
1134 // type (T::*)()
1135 // type (type::*)(T)
1136 // type (T::*)(T)
1137 // T (type::*)(T)
1138 // T (T::*)()
1139 // T (T::*)(T)
1140 case Type::MemberPointer: {
1141 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1142 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1143 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001144 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001145
Douglas Gregorf67875d2009-06-12 18:26:56 +00001146 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001147 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001148 MemPtrParam->getPointeeType(),
1149 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001150 Info, Deduced,
1151 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001152 return Result;
1153
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001154 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001155 QualType(MemPtrParam->getClass(), 0),
1156 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001157 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001158 }
1159
Anders Carlsson9a917e42009-06-12 22:56:54 +00001160 // (clang extension)
1161 //
Mike Stump1eb44332009-09-09 15:08:12 +00001162 // type(^)(T)
1163 // T(^)()
1164 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001165 case Type::BlockPointer: {
1166 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1167 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Anders Carlsson859ba502009-06-12 16:23:10 +00001169 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001170 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001172 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001173 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001174 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001175 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001176 }
1177
Douglas Gregor637a4092009-06-10 23:47:09 +00001178 case Type::TypeOfExpr:
1179 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001180 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001181 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001182 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001183
Douglas Gregord560d502009-06-04 00:21:18 +00001184 default:
1185 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001186 }
1187
1188 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001189 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001190}
1191
Douglas Gregorf67875d2009-06-12 18:26:56 +00001192static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001193DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001194 TemplateParameterList *TemplateParams,
1195 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001196 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001197 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001198 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001199 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001200 case TemplateArgument::Null:
1201 assert(false && "Null template argument in parameter list");
1202 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001203
1204 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001205 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001206 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001207 Arg.getAsType(), Info, Deduced, 0);
1208 Info.FirstArg = Param;
1209 Info.SecondArg = Arg;
1210 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001211
Douglas Gregor788cd062009-11-11 01:00:40 +00001212 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001213 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001214 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001215 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001216 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001217 Info.FirstArg = Param;
1218 Info.SecondArg = Arg;
1219 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001220
1221 case TemplateArgument::TemplateExpansion:
1222 llvm_unreachable("caller should handle pack expansions");
1223 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001224
Douglas Gregor199d9912009-06-05 00:53:49 +00001225 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001226 if (Arg.getKind() == TemplateArgument::Declaration &&
1227 Param.getAsDecl()->getCanonicalDecl() ==
1228 Arg.getAsDecl()->getCanonicalDecl())
1229 return Sema::TDK_Success;
1230
Douglas Gregorf67875d2009-06-12 18:26:56 +00001231 Info.FirstArg = Param;
1232 Info.SecondArg = Arg;
1233 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Douglas Gregor199d9912009-06-05 00:53:49 +00001235 case TemplateArgument::Integral:
1236 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001237 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001238 return Sema::TDK_Success;
1239
1240 Info.FirstArg = Param;
1241 Info.SecondArg = Arg;
1242 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001243 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001244
1245 if (Arg.getKind() == TemplateArgument::Expression) {
1246 Info.FirstArg = Param;
1247 Info.SecondArg = Arg;
1248 return Sema::TDK_NonDeducedMismatch;
1249 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001250
Douglas Gregorf67875d2009-06-12 18:26:56 +00001251 Info.FirstArg = Param;
1252 Info.SecondArg = Arg;
1253 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Douglas Gregor199d9912009-06-05 00:53:49 +00001255 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001256 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001257 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1258 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001259 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001260 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001261 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001262 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001263 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001264 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001265 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001266 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001267 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001268 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001269 Info, Deduced);
1270
Douglas Gregorf67875d2009-06-12 18:26:56 +00001271 Info.FirstArg = Param;
1272 Info.SecondArg = Arg;
1273 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001274 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Douglas Gregor199d9912009-06-05 00:53:49 +00001276 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001277 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001278 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001279 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001280 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregorf67875d2009-06-12 18:26:56 +00001283 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001284}
1285
Douglas Gregor20a55e22010-12-22 18:17:10 +00001286/// \brief Determine whether there is a template argument to be used for
1287/// deduction.
1288///
1289/// This routine "expands" argument packs in-place, overriding its input
1290/// parameters so that \c Args[ArgIdx] will be the available template argument.
1291///
1292/// \returns true if there is another template argument (which will be at
1293/// \c Args[ArgIdx]), false otherwise.
1294static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1295 unsigned &ArgIdx,
1296 unsigned &NumArgs) {
1297 if (ArgIdx == NumArgs)
1298 return false;
1299
1300 const TemplateArgument &Arg = Args[ArgIdx];
1301 if (Arg.getKind() != TemplateArgument::Pack)
1302 return true;
1303
1304 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1305 Args = Arg.pack_begin();
1306 NumArgs = Arg.pack_size();
1307 ArgIdx = 0;
1308 return ArgIdx < NumArgs;
1309}
1310
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001311/// \brief Determine whether the given set of template arguments has a pack
1312/// expansion that is not the last template argument.
1313static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1314 unsigned NumArgs) {
1315 unsigned ArgIdx = 0;
1316 while (ArgIdx < NumArgs) {
1317 const TemplateArgument &Arg = Args[ArgIdx];
1318
1319 // Unwrap argument packs.
1320 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1321 Args = Arg.pack_begin();
1322 NumArgs = Arg.pack_size();
1323 ArgIdx = 0;
1324 continue;
1325 }
1326
1327 ++ArgIdx;
1328 if (ArgIdx == NumArgs)
1329 return false;
1330
1331 if (Arg.isPackExpansion())
1332 return true;
1333 }
1334
1335 return false;
1336}
1337
Douglas Gregor20a55e22010-12-22 18:17:10 +00001338static Sema::TemplateDeductionResult
1339DeduceTemplateArguments(Sema &S,
1340 TemplateParameterList *TemplateParams,
1341 const TemplateArgument *Params, unsigned NumParams,
1342 const TemplateArgument *Args, unsigned NumArgs,
1343 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001344 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1345 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001346 // C++0x [temp.deduct.type]p9:
1347 // If the template argument list of P contains a pack expansion that is not
1348 // the last template argument, the entire template argument list is a
1349 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001350 if (hasPackExpansionBeforeEnd(Params, NumParams))
1351 return Sema::TDK_Success;
1352
Douglas Gregore02e2622010-12-22 21:19:48 +00001353 // C++0x [temp.deduct.type]p9:
1354 // If P has a form that contains <T> or <i>, then each argument Pi of the
1355 // respective template argument list P is compared with the corresponding
1356 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001357 unsigned ArgIdx = 0, ParamIdx = 0;
1358 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1359 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001360 // FIXME: Variadic templates.
1361 // What do we do if the argument is a pack expansion?
1362
Douglas Gregor20a55e22010-12-22 18:17:10 +00001363 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001364 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001365
1366 // Check whether we have enough arguments.
1367 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001368 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1369 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001370
Douglas Gregore02e2622010-12-22 21:19:48 +00001371 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001372 if (Sema::TemplateDeductionResult Result
1373 = DeduceTemplateArguments(S, TemplateParams,
1374 Params[ParamIdx], Args[ArgIdx],
1375 Info, Deduced))
1376 return Result;
1377
1378 // Move to the next argument.
1379 ++ArgIdx;
1380 continue;
1381 }
1382
Douglas Gregore02e2622010-12-22 21:19:48 +00001383 // The parameter is a pack expansion.
1384
1385 // C++0x [temp.deduct.type]p9:
1386 // If Pi is a pack expansion, then the pattern of Pi is compared with
1387 // each remaining argument in the template argument list of A. Each
1388 // comparison deduces template arguments for subsequent positions in the
1389 // template parameter packs expanded by Pi.
1390 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1391
1392 // Compute the set of template parameter indices that correspond to
1393 // parameter packs expanded by the pack expansion.
1394 llvm::SmallVector<unsigned, 2> PackIndices;
1395 {
1396 llvm::BitVector SawIndices(TemplateParams->size());
1397 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1398 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1399 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1400 unsigned Depth, Index;
1401 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1402 if (Depth == 0 && !SawIndices[Index]) {
1403 SawIndices[Index] = true;
1404 PackIndices.push_back(Index);
1405 }
1406 }
1407 }
1408 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1409
1410 // FIXME: If there are no remaining arguments, we can bail out early
1411 // and set any deduced parameter packs to an empty argument pack.
1412 // The latter part of this is a (minor) correctness issue.
1413
1414 // Save the deduced template arguments for each parameter pack expanded
1415 // by this pack expansion, then clear out the deduction.
1416 llvm::SmallVector<DeducedTemplateArgument, 2>
1417 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001418 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1419 NewlyDeducedPacks(PackIndices.size());
1420 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1421 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001422
1423 // Keep track of the deduced template arguments for each parameter pack
1424 // expanded by this pack expansion (the outer index) and for each
1425 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001426 bool HasAnyArguments = false;
1427 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1428 HasAnyArguments = true;
1429
1430 // Deduce template arguments from the pattern.
1431 if (Sema::TemplateDeductionResult Result
1432 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1433 Info, Deduced))
1434 return Result;
1435
1436 // Capture the deduced template arguments for each parameter pack expanded
1437 // by this pack expansion, add them to the list of arguments we've deduced
1438 // for that pack, then clear out the deduced argument.
1439 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1440 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1441 if (!DeducedArg.isNull()) {
1442 NewlyDeducedPacks[I].push_back(DeducedArg);
1443 DeducedArg = DeducedTemplateArgument();
1444 }
1445 }
1446
1447 ++ArgIdx;
1448 }
1449
1450 // Build argument packs for each of the parameter packs expanded by this
1451 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001452 if (Sema::TemplateDeductionResult Result
1453 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1454 Deduced, PackIndices, SavedPacks,
1455 NewlyDeducedPacks, Info))
1456 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001457 }
1458
1459 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001460 if (NumberOfArgumentsMustMatch &&
1461 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001462 return Sema::TDK_TooManyArguments;
1463
1464 return Sema::TDK_Success;
1465}
1466
Mike Stump1eb44332009-09-09 15:08:12 +00001467static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001468DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001469 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001470 const TemplateArgumentList &ParamList,
1471 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001472 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001473 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001474 return DeduceTemplateArguments(S, TemplateParams,
1475 ParamList.data(), ParamList.size(),
1476 ArgList.data(), ArgList.size(),
1477 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001478}
1479
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001480/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001481static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001482 const TemplateArgument &X,
1483 const TemplateArgument &Y) {
1484 if (X.getKind() != Y.getKind())
1485 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001487 switch (X.getKind()) {
1488 case TemplateArgument::Null:
1489 assert(false && "Comparing NULL template argument");
1490 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001492 case TemplateArgument::Type:
1493 return Context.getCanonicalType(X.getAsType()) ==
1494 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001496 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001497 return X.getAsDecl()->getCanonicalDecl() ==
1498 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Douglas Gregor788cd062009-11-11 01:00:40 +00001500 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001501 case TemplateArgument::TemplateExpansion:
1502 return Context.getCanonicalTemplateName(
1503 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1504 Context.getCanonicalTemplateName(
1505 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001506
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001507 case TemplateArgument::Integral:
1508 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Douglas Gregor788cd062009-11-11 01:00:40 +00001510 case TemplateArgument::Expression: {
1511 llvm::FoldingSetNodeID XID, YID;
1512 X.getAsExpr()->Profile(XID, Context, true);
1513 Y.getAsExpr()->Profile(YID, Context, true);
1514 return XID == YID;
1515 }
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001517 case TemplateArgument::Pack:
1518 if (X.pack_size() != Y.pack_size())
1519 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001520
1521 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1522 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001523 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001524 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001525 if (!isSameTemplateArg(Context, *XP, *YP))
1526 return false;
1527
1528 return true;
1529 }
1530
1531 return false;
1532}
1533
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001534/// \brief Allocate a TemplateArgumentLoc where all locations have
1535/// been initialized to the given location.
1536///
1537/// \param S The semantic analysis object.
1538///
1539/// \param The template argument we are producing template argument
1540/// location information for.
1541///
1542/// \param NTTPType For a declaration template argument, the type of
1543/// the non-type template parameter that corresponds to this template
1544/// argument.
1545///
1546/// \param Loc The source location to use for the resulting template
1547/// argument.
1548static TemplateArgumentLoc
1549getTrivialTemplateArgumentLoc(Sema &S,
1550 const TemplateArgument &Arg,
1551 QualType NTTPType,
1552 SourceLocation Loc) {
1553 switch (Arg.getKind()) {
1554 case TemplateArgument::Null:
1555 llvm_unreachable("Can't get a NULL template argument here");
1556 break;
1557
1558 case TemplateArgument::Type:
1559 return TemplateArgumentLoc(Arg,
1560 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1561
1562 case TemplateArgument::Declaration: {
1563 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001564 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001565 .takeAs<Expr>();
1566 return TemplateArgumentLoc(TemplateArgument(E), E);
1567 }
1568
1569 case TemplateArgument::Integral: {
1570 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001571 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001572 return TemplateArgumentLoc(TemplateArgument(E), E);
1573 }
1574
1575 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001576 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1577
1578 case TemplateArgument::TemplateExpansion:
1579 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1580
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001581 case TemplateArgument::Expression:
1582 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1583
1584 case TemplateArgument::Pack:
1585 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1586 }
1587
1588 return TemplateArgumentLoc();
1589}
1590
1591
1592/// \brief Convert the given deduced template argument and add it to the set of
1593/// fully-converted template arguments.
1594static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1595 DeducedTemplateArgument Arg,
1596 NamedDecl *Template,
1597 QualType NTTPType,
1598 TemplateDeductionInfo &Info,
1599 bool InFunctionTemplate,
1600 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1601 if (Arg.getKind() == TemplateArgument::Pack) {
1602 // This is a template argument pack, so check each of its arguments against
1603 // the template parameter.
1604 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1605 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001606 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001607 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001608 // When converting the deduced template argument, append it to the
1609 // general output list. We need to do this so that the template argument
1610 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001611 DeducedTemplateArgument InnerArg(*PA);
1612 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1613 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1614 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001615 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001616 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001617
1618 // Move the converted template argument into our argument pack.
1619 PackedArgsBuilder.push_back(Output.back());
1620 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001621 }
1622
1623 // Create the resulting argument pack.
1624 TemplateArgument *PackedArgs = 0;
1625 if (!PackedArgsBuilder.empty()) {
1626 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1627 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1628 }
1629 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1630 return false;
1631 }
1632
1633 // Convert the deduced template argument into a template
1634 // argument that we can check, almost as if the user had written
1635 // the template argument explicitly.
1636 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1637 Info.getLocation());
1638
1639 // Check the template argument, converting it as necessary.
1640 return S.CheckTemplateArgument(Param, ArgLoc,
1641 Template,
1642 Template->getLocation(),
1643 Template->getSourceRange().getEnd(),
1644 Output,
1645 InFunctionTemplate
1646 ? (Arg.wasDeducedFromArrayBound()
1647 ? Sema::CTAK_DeducedFromArrayBound
1648 : Sema::CTAK_Deduced)
1649 : Sema::CTAK_Specified);
1650}
1651
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001652/// Complete template argument deduction for a class template partial
1653/// specialization.
1654static Sema::TemplateDeductionResult
1655FinishTemplateArgumentDeduction(Sema &S,
1656 ClassTemplatePartialSpecializationDecl *Partial,
1657 const TemplateArgumentList &TemplateArgs,
1658 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001659 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001660 // Trap errors.
1661 Sema::SFINAETrap Trap(S);
1662
1663 Sema::ContextRAII SavedContext(S, Partial);
1664
1665 // C++ [temp.deduct.type]p2:
1666 // [...] or if any template argument remains neither deduced nor
1667 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001668 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001669 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1670 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001671 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001672 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001673 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001674 return Sema::TDK_Incomplete;
1675 }
1676
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001677 // We have deduced this argument, so it still needs to be
1678 // checked and converted.
1679
1680 // First, for a non-type template parameter type that is
1681 // initialized by a declaration, we need the type of the
1682 // corresponding non-type template parameter.
1683 QualType NTTPType;
1684 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001685 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001686 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001687 if (NTTPType->isDependentType()) {
1688 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1689 Builder.data(), Builder.size());
1690 NTTPType = S.SubstType(NTTPType,
1691 MultiLevelTemplateArgumentList(TemplateArgs),
1692 NTTP->getLocation(),
1693 NTTP->getDeclName());
1694 if (NTTPType.isNull()) {
1695 Info.Param = makeTemplateParameter(Param);
1696 // FIXME: These template arguments are temporary. Free them!
1697 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1698 Builder.data(),
1699 Builder.size()));
1700 return Sema::TDK_SubstitutionFailure;
1701 }
1702 }
1703 }
1704
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001705 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1706 Partial, NTTPType, Info, false,
1707 Builder)) {
1708 Info.Param = makeTemplateParameter(Param);
1709 // FIXME: These template arguments are temporary. Free them!
1710 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1711 Builder.size()));
1712 return Sema::TDK_SubstitutionFailure;
1713 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001714 }
1715
1716 // Form the template argument list from the deduced template arguments.
1717 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001718 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1719 Builder.size());
1720
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001721 Info.reset(DeducedArgumentList);
1722
1723 // Substitute the deduced template arguments into the template
1724 // arguments of the class template partial specialization, and
1725 // verify that the instantiated template arguments are both valid
1726 // and are equivalent to the template arguments originally provided
1727 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001728 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001729 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1730 const TemplateArgumentLoc *PartialTemplateArgs
1731 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001732
1733 // Note that we don't provide the langle and rangle locations.
1734 TemplateArgumentListInfo InstArgs;
1735
Douglas Gregore02e2622010-12-22 21:19:48 +00001736 if (S.Subst(PartialTemplateArgs,
1737 Partial->getNumTemplateArgsAsWritten(),
1738 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1739 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1740 if (ParamIdx >= Partial->getTemplateParameters()->size())
1741 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1742
1743 Decl *Param
1744 = const_cast<NamedDecl *>(
1745 Partial->getTemplateParameters()->getParam(ParamIdx));
1746 Info.Param = makeTemplateParameter(Param);
1747 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1748 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001749 }
1750
Douglas Gregor910f8002010-11-07 23:05:16 +00001751 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001752 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001753 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001754 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001755
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001756 TemplateParameterList *TemplateParams
1757 = ClassTemplate->getTemplateParameters();
1758 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001759 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001760 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001761 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001762 Info.FirstArg = TemplateArgs[I];
1763 Info.SecondArg = InstArg;
1764 return Sema::TDK_NonDeducedMismatch;
1765 }
1766 }
1767
1768 if (Trap.hasErrorOccurred())
1769 return Sema::TDK_SubstitutionFailure;
1770
1771 return Sema::TDK_Success;
1772}
1773
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001774/// \brief Perform template argument deduction to determine whether
1775/// the given template arguments match the given class template
1776/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001777Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001778Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001779 const TemplateArgumentList &TemplateArgs,
1780 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001781 // C++ [temp.class.spec.match]p2:
1782 // A partial specialization matches a given actual template
1783 // argument list if the template arguments of the partial
1784 // specialization can be deduced from the actual template argument
1785 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001786 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001787 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001788 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001789 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001790 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001791 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001792 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001793 TemplateArgs, Info, Deduced))
1794 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001795
Douglas Gregor637a4092009-06-10 23:47:09 +00001796 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001797 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001798 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001799 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001800
Douglas Gregorbb260412009-06-14 08:02:22 +00001801 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001802 return Sema::TDK_SubstitutionFailure;
1803
1804 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1805 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001806}
Douglas Gregor031a5882009-06-13 00:26:55 +00001807
Douglas Gregor41128772009-06-26 23:27:24 +00001808/// \brief Determine whether the given type T is a simple-template-id type.
1809static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001810 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001811 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001812 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor41128772009-06-26 23:27:24 +00001814 return false;
1815}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001816
1817/// \brief Substitute the explicitly-provided template arguments into the
1818/// given function template according to C++ [temp.arg.explicit].
1819///
1820/// \param FunctionTemplate the function template into which the explicit
1821/// template arguments will be substituted.
1822///
Mike Stump1eb44332009-09-09 15:08:12 +00001823/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001824/// arguments.
1825///
Mike Stump1eb44332009-09-09 15:08:12 +00001826/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001827/// with the converted and checked explicit template arguments.
1828///
Mike Stump1eb44332009-09-09 15:08:12 +00001829/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001830/// parameters.
1831///
1832/// \param FunctionType if non-NULL, the result type of the function template
1833/// will also be instantiated and the pointed-to value will be updated with
1834/// the instantiated function type.
1835///
1836/// \param Info if substitution fails for any reason, this object will be
1837/// populated with more information about the failure.
1838///
1839/// \returns TDK_Success if substitution was successful, or some failure
1840/// condition.
1841Sema::TemplateDeductionResult
1842Sema::SubstituteExplicitTemplateArguments(
1843 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001844 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001845 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001846 llvm::SmallVectorImpl<QualType> &ParamTypes,
1847 QualType *FunctionType,
1848 TemplateDeductionInfo &Info) {
1849 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1850 TemplateParameterList *TemplateParams
1851 = FunctionTemplate->getTemplateParameters();
1852
John McCalld5532b62009-11-23 01:53:49 +00001853 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001854 // No arguments to substitute; just copy over the parameter types and
1855 // fill in the function type.
1856 for (FunctionDecl::param_iterator P = Function->param_begin(),
1857 PEnd = Function->param_end();
1858 P != PEnd;
1859 ++P)
1860 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregor83314aa2009-07-08 20:55:45 +00001862 if (FunctionType)
1863 *FunctionType = Function->getType();
1864 return TDK_Success;
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor83314aa2009-07-08 20:55:45 +00001867 // Substitution of the explicit template arguments into a function template
1868 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 SFINAETrap Trap(*this);
1870
Douglas Gregor83314aa2009-07-08 20:55:45 +00001871 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001872 // Template arguments that are present shall be specified in the
1873 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001874 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001875 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001876 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001877
1878 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001879 // explicitly-specified template arguments against this function template,
1880 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001882 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001883 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1884 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001885 if (Inst)
1886 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Douglas Gregor83314aa2009-07-08 20:55:45 +00001888 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001889 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001890 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001891 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001892 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001893 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001894 if (Index >= TemplateParams->size())
1895 Index = TemplateParams->size() - 1;
1896 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001897 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor83314aa2009-07-08 20:55:45 +00001900 // Form the template argument list from the explicitly-specified
1901 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001902 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001903 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001904 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001905
John McCalldf41f182010-10-12 19:40:14 +00001906 // Template argument deduction and the final substitution should be
1907 // done in the context of the templated declaration. Explicit
1908 // argument substitution, on the other hand, needs to happen in the
1909 // calling context.
1910 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1911
Douglas Gregord3731192011-01-10 07:32:04 +00001912 // If we deduced template arguments for a template parameter pack,
1913 // note that the template argument pack is partially substituted and record
1914 // the explicit template arguments. They'll be used as part of deduction
1915 // for this template parameter pack.
1916 bool HasPartiallySubstitutedPack = false;
1917 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1918 const TemplateArgument &Arg = Builder[I];
1919 if (Arg.getKind() == TemplateArgument::Pack) {
1920 HasPartiallySubstitutedPack = true;
1921 CurrentInstantiationScope->SetPartiallySubstitutedPack(
1922 TemplateParams->getParam(I),
1923 Arg.pack_begin(),
1924 Arg.pack_size());
1925 break;
1926 }
1927 }
1928
Douglas Gregor83314aa2009-07-08 20:55:45 +00001929 // Instantiate the types of each of the function parameters given the
1930 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001931 if (SubstParmTypes(Function->getLocation(),
1932 Function->param_begin(), Function->getNumParams(),
1933 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1934 ParamTypes))
1935 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936
1937 // If the caller wants a full function type back, instantiate the return
1938 // type and form that function type.
1939 if (FunctionType) {
1940 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001941 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001942 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001943 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001944
1945 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001946 = SubstType(Proto->getResultType(),
1947 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1948 Function->getTypeSpecStartLoc(),
1949 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001950 if (ResultType.isNull() || Trap.hasErrorOccurred())
1951 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001952
1953 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001954 ParamTypes.data(), ParamTypes.size(),
1955 Proto->isVariadic(),
1956 Proto->getTypeQuals(),
1957 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001958 Function->getDeclName(),
1959 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001960 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1961 return TDK_SubstitutionFailure;
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Douglas Gregor83314aa2009-07-08 20:55:45 +00001964 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001965 // Trailing template arguments that can be deduced (14.8.2) may be
1966 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001967 // template arguments can be deduced, they may all be omitted; in this
1968 // case, the empty template argument list <> itself may also be omitted.
1969 //
Douglas Gregord3731192011-01-10 07:32:04 +00001970 // Take all of the explicitly-specified arguments and put them into
1971 // the set of deduced template arguments. Explicitly-specified
1972 // parameter packs, however, will be set to NULL since the deduction
1973 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001974 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00001975 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
1976 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
1977 if (Arg.getKind() == TemplateArgument::Pack)
1978 Deduced.push_back(DeducedTemplateArgument());
1979 else
1980 Deduced.push_back(Arg);
1981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor83314aa2009-07-08 20:55:45 +00001983 return TDK_Success;
1984}
1985
Mike Stump1eb44332009-09-09 15:08:12 +00001986/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001987/// checking the deduced template arguments for completeness and forming
1988/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001989Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001990Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001991 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1992 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001993 FunctionDecl *&Specialization,
1994 TemplateDeductionInfo &Info) {
1995 TemplateParameterList *TemplateParams
1996 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Douglas Gregor83314aa2009-07-08 20:55:45 +00001998 // Template argument deduction for function templates in a SFINAE context.
1999 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002000 SFINAETrap Trap(*this);
2001
Douglas Gregor83314aa2009-07-08 20:55:45 +00002002 // Enter a new template instantiation context while we instantiate the
2003 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002004 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002005 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002006 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2007 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002008 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002009 return TDK_InstantiationDepth;
2010
John McCall96db3102010-04-29 01:18:58 +00002011 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002012
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002013 // C++ [temp.deduct.type]p2:
2014 // [...] or if any template argument remains neither deduced nor
2015 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002016 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002017 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2018 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002019
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002020 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002021 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002022 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002023 // argument, because it was explicitly-specified. Just record the
2024 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002025 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002026 continue;
2027 }
2028
2029 // We have deduced this argument, so it still needs to be
2030 // checked and converted.
2031
2032 // First, for a non-type template parameter type that is
2033 // initialized by a declaration, we need the type of the
2034 // corresponding non-type template parameter.
2035 QualType NTTPType;
2036 if (NonTypeTemplateParmDecl *NTTP
2037 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002038 NTTPType = NTTP->getType();
2039 if (NTTPType->isDependentType()) {
2040 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2041 Builder.data(), Builder.size());
2042 NTTPType = SubstType(NTTPType,
2043 MultiLevelTemplateArgumentList(TemplateArgs),
2044 NTTP->getLocation(),
2045 NTTP->getDeclName());
2046 if (NTTPType.isNull()) {
2047 Info.Param = makeTemplateParameter(Param);
2048 // FIXME: These template arguments are temporary. Free them!
2049 Info.reset(TemplateArgumentList::CreateCopy(Context,
2050 Builder.data(),
2051 Builder.size()));
2052 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002053 }
2054 }
2055 }
2056
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002057 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2058 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002059 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002060 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002061 // FIXME: These template arguments are temporary. Free them!
2062 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002063 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002064 return TDK_SubstitutionFailure;
2065 }
2066
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002067 continue;
2068 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002069
2070 // C++0x [temp.arg.explicit]p3:
2071 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2072 // be deduced to an empty sequence of template arguments.
2073 // FIXME: Where did the word "trailing" come from?
2074 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002075 // We may have had explicitly-specified template arguments for this
2076 // template parameter pack. If so, our empty deduction extends the
2077 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2078 const TemplateArgument *ExplicitArgs;
2079 unsigned NumExplicitArgs;
2080 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2081 &NumExplicitArgs)
2082 == Param)
2083 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2084 else
2085 Builder.push_back(TemplateArgument(0, 0));
2086
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002087 continue;
2088 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002089
2090 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002091 TemplateArgumentLoc DefArg
2092 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2093 FunctionTemplate->getLocation(),
2094 FunctionTemplate->getSourceRange().getEnd(),
2095 Param,
2096 Builder);
2097
2098 // If there was no default argument, deduction is incomplete.
2099 if (DefArg.getArgument().isNull()) {
2100 Info.Param = makeTemplateParameter(
2101 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2102 return TDK_Incomplete;
2103 }
2104
2105 // Check whether we can actually use the default argument.
2106 if (CheckTemplateArgument(Param, DefArg,
2107 FunctionTemplate,
2108 FunctionTemplate->getLocation(),
2109 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002110 Builder,
2111 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002112 Info.Param = makeTemplateParameter(
2113 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002114 // FIXME: These template arguments are temporary. Free them!
2115 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2116 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002117 return TDK_SubstitutionFailure;
2118 }
2119
2120 // If we get here, we successfully used the default template argument.
2121 }
2122
2123 // Form the template argument list from the deduced template arguments.
2124 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002125 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002126 Info.reset(DeducedArgumentList);
2127
Mike Stump1eb44332009-09-09 15:08:12 +00002128 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002129 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002130 DeclContext *Owner = FunctionTemplate->getDeclContext();
2131 if (FunctionTemplate->getFriendObjectKind())
2132 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002133 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002134 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002135 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002136 if (!Specialization)
2137 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Douglas Gregorf8825742009-09-15 18:26:13 +00002139 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2140 FunctionTemplate->getCanonicalDecl());
2141
Mike Stump1eb44332009-09-09 15:08:12 +00002142 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002143 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002144 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2145 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002146 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Douglas Gregor83314aa2009-07-08 20:55:45 +00002148 // There may have been an error that did not prevent us from constructing a
2149 // declaration. Mark the declaration invalid and return with a substitution
2150 // failure.
2151 if (Trap.hasErrorOccurred()) {
2152 Specialization->setInvalidDecl(true);
2153 return TDK_SubstitutionFailure;
2154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregor9b623632010-10-12 23:32:35 +00002156 // If we suppressed any diagnostics while performing template argument
2157 // deduction, and if we haven't already instantiated this declaration,
2158 // keep track of these diagnostics. They'll be emitted if this specialization
2159 // is actually used.
2160 if (Info.diag_begin() != Info.diag_end()) {
2161 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2162 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2163 if (Pos == SuppressedDiagnostics.end())
2164 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2165 .append(Info.diag_begin(), Info.diag_end());
2166 }
2167
Mike Stump1eb44332009-09-09 15:08:12 +00002168 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002169}
2170
John McCall9c72c602010-08-27 09:08:28 +00002171/// Gets the type of a function for template-argument-deducton
2172/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002173static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002174 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002175 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002176 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002177 if (Method->isInstance()) {
2178 // An instance method that's referenced in a form that doesn't
2179 // look like a member pointer is just invalid.
2180 if (!R.HasFormOfMemberPointer) return QualType();
2181
John McCalleff92132010-02-02 02:21:27 +00002182 return Context.getMemberPointerType(Fn->getType(),
2183 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002184 }
2185
2186 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002187 return Context.getPointerType(Fn->getType());
2188}
2189
2190/// Apply the deduction rules for overload sets.
2191///
2192/// \return the null type if this argument should be treated as an
2193/// undeduced context
2194static QualType
2195ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002196 Expr *Arg, QualType ParamType,
2197 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002198
2199 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002200
John McCall9c72c602010-08-27 09:08:28 +00002201 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002202
Douglas Gregor75f21af2010-08-30 21:04:23 +00002203 // C++0x [temp.deduct.call]p4
2204 unsigned TDF = 0;
2205 if (ParamWasReference)
2206 TDF |= TDF_ParamWithReferenceType;
2207 if (R.IsAddressOfOperand)
2208 TDF |= TDF_IgnoreQualifiers;
2209
John McCalleff92132010-02-02 02:21:27 +00002210 // If there were explicit template arguments, we can only find
2211 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2212 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002213 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002214 // But we can still look for an explicit specialization.
2215 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002216 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002217 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002218 return QualType();
2219 }
2220
2221 // C++0x [temp.deduct.call]p6:
2222 // When P is a function type, pointer to function type, or pointer
2223 // to member function type:
2224
2225 if (!ParamType->isFunctionType() &&
2226 !ParamType->isFunctionPointerType() &&
2227 !ParamType->isMemberFunctionPointerType())
2228 return QualType();
2229
2230 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002231 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2232 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002233 NamedDecl *D = (*I)->getUnderlyingDecl();
2234
2235 // - If the argument is an overload set containing one or more
2236 // function templates, the parameter is treated as a
2237 // non-deduced context.
2238 if (isa<FunctionTemplateDecl>(D))
2239 return QualType();
2240
2241 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002242 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2243 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002244
Douglas Gregor75f21af2010-08-30 21:04:23 +00002245 // Function-to-pointer conversion.
2246 if (!ParamWasReference && ParamType->isPointerType() &&
2247 ArgType->isFunctionType())
2248 ArgType = S.Context.getPointerType(ArgType);
2249
John McCalleff92132010-02-02 02:21:27 +00002250 // - If the argument is an overload set (not containing function
2251 // templates), trial argument deduction is attempted using each
2252 // of the members of the set. If deduction succeeds for only one
2253 // of the overload set members, that member is used as the
2254 // argument value for the deduction. If deduction succeeds for
2255 // more than one member of the overload set the parameter is
2256 // treated as a non-deduced context.
2257
2258 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2259 // Type deduction is done independently for each P/A pair, and
2260 // the deduced template argument values are then combined.
2261 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002262 llvm::SmallVector<DeducedTemplateArgument, 8>
2263 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002264 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002265 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002266 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002267 ParamType, ArgType,
2268 Info, Deduced, TDF);
2269 if (Result) continue;
2270 if (!Match.isNull()) return QualType();
2271 Match = ArgType;
2272 }
2273
2274 return Match;
2275}
2276
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002277/// \brief Perform the adjustments to the parameter and argument types
2278/// described in C++ [temp.deduct.call].
2279///
2280/// \returns true if the caller should not attempt to perform any template
2281/// argument deduction based on this P/A pair.
2282static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2283 TemplateParameterList *TemplateParams,
2284 QualType &ParamType,
2285 QualType &ArgType,
2286 Expr *Arg,
2287 unsigned &TDF) {
2288 // C++0x [temp.deduct.call]p3:
2289 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2290 // are ignored for type deduction.
2291 if (ParamType.getCVRQualifiers())
2292 ParamType = ParamType.getLocalUnqualifiedType();
2293 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2294 if (ParamRefType) {
2295 // [...] If P is a reference type, the type referred to by P is used
2296 // for type deduction.
2297 ParamType = ParamRefType->getPointeeType();
2298 }
2299
2300 // Overload sets usually make this parameter an undeduced
2301 // context, but there are sometimes special circumstances.
2302 if (ArgType == S.Context.OverloadTy) {
2303 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2304 Arg, ParamType,
2305 ParamRefType != 0);
2306 if (ArgType.isNull())
2307 return true;
2308 }
2309
2310 if (ParamRefType) {
2311 // C++0x [temp.deduct.call]p3:
2312 // [...] If P is of the form T&&, where T is a template parameter, and
2313 // the argument is an lvalue, the type A& is used in place of A for
2314 // type deduction.
2315 if (ParamRefType->isRValueReferenceType() &&
2316 ParamRefType->getAs<TemplateTypeParmType>() &&
2317 Arg->isLValue())
2318 ArgType = S.Context.getLValueReferenceType(ArgType);
2319 } else {
2320 // C++ [temp.deduct.call]p2:
2321 // If P is not a reference type:
2322 // - If A is an array type, the pointer type produced by the
2323 // array-to-pointer standard conversion (4.2) is used in place of
2324 // A for type deduction; otherwise,
2325 if (ArgType->isArrayType())
2326 ArgType = S.Context.getArrayDecayedType(ArgType);
2327 // - If A is a function type, the pointer type produced by the
2328 // function-to-pointer standard conversion (4.3) is used in place
2329 // of A for type deduction; otherwise,
2330 else if (ArgType->isFunctionType())
2331 ArgType = S.Context.getPointerType(ArgType);
2332 else {
2333 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2334 // type are ignored for type deduction.
2335 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2336 if (ArgType.getCVRQualifiers())
2337 ArgType = ArgType.getUnqualifiedType();
2338 }
2339 }
2340
2341 // C++0x [temp.deduct.call]p4:
2342 // In general, the deduction process attempts to find template argument
2343 // values that will make the deduced A identical to A (after the type A
2344 // is transformed as described above). [...]
2345 TDF = TDF_SkipNonDependent;
2346
2347 // - If the original P is a reference type, the deduced A (i.e., the
2348 // type referred to by the reference) can be more cv-qualified than
2349 // the transformed A.
2350 if (ParamRefType)
2351 TDF |= TDF_ParamWithReferenceType;
2352 // - The transformed A can be another pointer or pointer to member
2353 // type that can be converted to the deduced A via a qualification
2354 // conversion (4.4).
2355 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2356 ArgType->isObjCObjectPointerType())
2357 TDF |= TDF_IgnoreQualifiers;
2358 // - If P is a class and P has the form simple-template-id, then the
2359 // transformed A can be a derived class of the deduced A. Likewise,
2360 // if P is a pointer to a class of the form simple-template-id, the
2361 // transformed A can be a pointer to a derived class pointed to by
2362 // the deduced A.
2363 if (isSimpleTemplateIdType(ParamType) ||
2364 (isa<PointerType>(ParamType) &&
2365 isSimpleTemplateIdType(
2366 ParamType->getAs<PointerType>()->getPointeeType())))
2367 TDF |= TDF_DerivedClass;
2368
2369 return false;
2370}
2371
Douglas Gregore53060f2009-06-25 22:08:12 +00002372/// \brief Perform template argument deduction from a function call
2373/// (C++ [temp.deduct.call]).
2374///
2375/// \param FunctionTemplate the function template for which we are performing
2376/// template argument deduction.
2377///
Douglas Gregor48026d22010-01-11 18:40:55 +00002378/// \param ExplicitTemplateArguments the explicit template arguments provided
2379/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002380///
Douglas Gregore53060f2009-06-25 22:08:12 +00002381/// \param Args the function call arguments
2382///
2383/// \param NumArgs the number of arguments in Args
2384///
Douglas Gregor48026d22010-01-11 18:40:55 +00002385/// \param Name the name of the function being called. This is only significant
2386/// when the function template is a conversion function template, in which
2387/// case this routine will also perform template argument deduction based on
2388/// the function to which
2389///
Douglas Gregore53060f2009-06-25 22:08:12 +00002390/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002391/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002392/// template argument deduction.
2393///
2394/// \param Info the argument will be updated to provide additional information
2395/// about template argument deduction.
2396///
2397/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002398Sema::TemplateDeductionResult
2399Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002400 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002401 Expr **Args, unsigned NumArgs,
2402 FunctionDecl *&Specialization,
2403 TemplateDeductionInfo &Info) {
2404 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002405
Douglas Gregore53060f2009-06-25 22:08:12 +00002406 // C++ [temp.deduct.call]p1:
2407 // Template argument deduction is done by comparing each function template
2408 // parameter type (call it P) with the type of the corresponding argument
2409 // of the call (call it A) as described below.
2410 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002411 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002412 return TDK_TooFewArguments;
2413 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002414 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002415 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002416 if (Proto->isTemplateVariadic())
2417 /* Do nothing */;
2418 else if (Proto->isVariadic())
2419 CheckArgs = Function->getNumParams();
2420 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002421 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002422 }
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002424 // The types of the parameters from which we will perform template argument
2425 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002426 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002427 TemplateParameterList *TemplateParams
2428 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002429 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002430 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002431 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002432 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002433 TemplateDeductionResult Result =
2434 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002435 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002436 Deduced,
2437 ParamTypes,
2438 0,
2439 Info);
2440 if (Result)
2441 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002442
2443 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002444 } else {
2445 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002446 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002447 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002450 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002451 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002452 unsigned ArgIdx = 0;
2453 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2454 ParamIdx != NumParams; ++ParamIdx) {
2455 QualType ParamType = ParamTypes[ParamIdx];
2456
2457 const PackExpansionType *ParamExpansion
2458 = dyn_cast<PackExpansionType>(ParamType);
2459 if (!ParamExpansion) {
2460 // Simple case: matching a function parameter to a function argument.
2461 if (ArgIdx >= CheckArgs)
2462 break;
2463
2464 Expr *Arg = Args[ArgIdx++];
2465 QualType ArgType = Arg->getType();
2466 unsigned TDF = 0;
2467 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2468 ParamType, ArgType, Arg,
2469 TDF))
2470 continue;
2471
2472 if (TemplateDeductionResult Result
2473 = ::DeduceTemplateArguments(*this, TemplateParams,
2474 ParamType, ArgType, Info, Deduced,
2475 TDF))
2476 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002478 // FIXME: we need to check that the deduced A is the same as A,
2479 // modulo the various allowed differences.
2480 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002481 }
2482
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002483 // C++0x [temp.deduct.call]p1:
2484 // For a function parameter pack that occurs at the end of the
2485 // parameter-declaration-list, the type A of each remaining argument of
2486 // the call is compared with the type P of the declarator-id of the
2487 // function parameter pack. Each comparison deduces template arguments
2488 // for subsequent positions in the template parameter packs expanded by
2489 // the function parameter pack.
2490 QualType ParamPattern = ParamExpansion->getPattern();
2491 llvm::SmallVector<unsigned, 2> PackIndices;
2492 {
2493 llvm::BitVector SawIndices(TemplateParams->size());
2494 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2495 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2496 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2497 unsigned Depth, Index;
2498 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2499 if (Depth == 0 && !SawIndices[Index]) {
2500 SawIndices[Index] = true;
2501 PackIndices.push_back(Index);
2502 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002503 }
2504 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002505 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2506
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002507 // Keep track of the deduced template arguments for each parameter pack
2508 // expanded by this pack expansion (the outer index) and for each
2509 // template argument (the inner SmallVectors).
2510 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002511 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002512 llvm::SmallVector<DeducedTemplateArgument, 2>
2513 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002514 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2515 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002516 bool HasAnyArguments = false;
2517 for (; ArgIdx < NumArgs; ++ArgIdx) {
2518 HasAnyArguments = true;
2519
2520 ParamType = ParamPattern;
2521 Expr *Arg = Args[ArgIdx];
2522 QualType ArgType = Arg->getType();
2523 unsigned TDF = 0;
2524 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2525 ParamType, ArgType, Arg,
2526 TDF)) {
2527 // We can't actually perform any deduction for this argument, so stop
2528 // deduction at this point.
2529 ++ArgIdx;
2530 break;
2531 }
2532
2533 if (TemplateDeductionResult Result
2534 = ::DeduceTemplateArguments(*this, TemplateParams,
2535 ParamType, ArgType, Info, Deduced,
2536 TDF))
2537 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002539 // Capture the deduced template arguments for each parameter pack expanded
2540 // by this pack expansion, add them to the list of arguments we've deduced
2541 // for that pack, then clear out the deduced argument.
2542 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2543 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2544 if (!DeducedArg.isNull()) {
2545 NewlyDeducedPacks[I].push_back(DeducedArg);
2546 DeducedArg = DeducedTemplateArgument();
2547 }
2548 }
2549 }
2550
2551 // Build argument packs for each of the parameter packs expanded by this
2552 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002553 if (Sema::TemplateDeductionResult Result
2554 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2555 Deduced, PackIndices, SavedPacks,
2556 NewlyDeducedPacks, Info))
2557 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002559 // After we've matching against a parameter pack, we're done.
2560 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002561 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002562
Mike Stump1eb44332009-09-09 15:08:12 +00002563 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002564 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002565 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002566}
2567
Douglas Gregor83314aa2009-07-08 20:55:45 +00002568/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002569/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2570/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002571///
2572/// \param FunctionTemplate the function template for which we are performing
2573/// template argument deduction.
2574///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002575/// \param ExplicitTemplateArguments the explicitly-specified template
2576/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002577///
2578/// \param ArgFunctionType the function type that will be used as the
2579/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002580/// function template's function type. This type may be NULL, if there is no
2581/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002582///
2583/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002584/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002585/// template argument deduction.
2586///
2587/// \param Info the argument will be updated to provide additional information
2588/// about template argument deduction.
2589///
2590/// \returns the result of template argument deduction.
2591Sema::TemplateDeductionResult
2592Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002593 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002594 QualType ArgFunctionType,
2595 FunctionDecl *&Specialization,
2596 TemplateDeductionInfo &Info) {
2597 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2598 TemplateParameterList *TemplateParams
2599 = FunctionTemplate->getTemplateParameters();
2600 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Douglas Gregor83314aa2009-07-08 20:55:45 +00002602 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002603 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002604 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2605 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002606 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002607 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002608 if (TemplateDeductionResult Result
2609 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002610 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002611 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002612 &FunctionType, Info))
2613 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002614
2615 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002616 }
2617
2618 // Template argument deduction for function templates in a SFINAE context.
2619 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002620 SFINAETrap Trap(*this);
2621
John McCalleff92132010-02-02 02:21:27 +00002622 Deduced.resize(TemplateParams->size());
2623
Douglas Gregor4b52e252009-12-21 23:17:24 +00002624 if (!ArgFunctionType.isNull()) {
2625 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002626 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002627 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002628 FunctionType, ArgFunctionType, Info,
2629 Deduced, 0))
2630 return Result;
2631 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002632
2633 if (TemplateDeductionResult Result
2634 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2635 NumExplicitlySpecified,
2636 Specialization, Info))
2637 return Result;
2638
2639 // If the requested function type does not match the actual type of the
2640 // specialization, template argument deduction fails.
2641 if (!ArgFunctionType.isNull() &&
2642 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2643 return TDK_NonDeducedMismatch;
2644
2645 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002646}
2647
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002648/// \brief Deduce template arguments for a templated conversion
2649/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2650/// conversion function template specialization.
2651Sema::TemplateDeductionResult
2652Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2653 QualType ToType,
2654 CXXConversionDecl *&Specialization,
2655 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002656 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002657 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2658 QualType FromType = Conv->getConversionType();
2659
2660 // Canonicalize the types for deduction.
2661 QualType P = Context.getCanonicalType(FromType);
2662 QualType A = Context.getCanonicalType(ToType);
2663
2664 // C++0x [temp.deduct.conv]p3:
2665 // If P is a reference type, the type referred to by P is used for
2666 // type deduction.
2667 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2668 P = PRef->getPointeeType();
2669
2670 // C++0x [temp.deduct.conv]p3:
2671 // If A is a reference type, the type referred to by A is used
2672 // for type deduction.
2673 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2674 A = ARef->getPointeeType();
2675 // C++ [temp.deduct.conv]p2:
2676 //
Mike Stump1eb44332009-09-09 15:08:12 +00002677 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002678 else {
2679 assert(!A->isReferenceType() && "Reference types were handled above");
2680
2681 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002682 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002683 // of P for type deduction; otherwise,
2684 if (P->isArrayType())
2685 P = Context.getArrayDecayedType(P);
2686 // - If P is a function type, the pointer type produced by the
2687 // function-to-pointer standard conversion (4.3) is used in
2688 // place of P for type deduction; otherwise,
2689 else if (P->isFunctionType())
2690 P = Context.getPointerType(P);
2691 // - If P is a cv-qualified type, the top level cv-qualifiers of
2692 // P’s type are ignored for type deduction.
2693 else
2694 P = P.getUnqualifiedType();
2695
2696 // C++0x [temp.deduct.conv]p3:
2697 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2698 // type are ignored for type deduction.
2699 A = A.getUnqualifiedType();
2700 }
2701
2702 // Template argument deduction for function templates in a SFINAE context.
2703 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002704 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002705
2706 // C++ [temp.deduct.conv]p1:
2707 // Template argument deduction is done by comparing the return
2708 // type of the template conversion function (call it P) with the
2709 // type that is required as the result of the conversion (call it
2710 // A) as described in 14.8.2.4.
2711 TemplateParameterList *TemplateParams
2712 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002713 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002714 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002715
2716 // C++0x [temp.deduct.conv]p4:
2717 // In general, the deduction process attempts to find template
2718 // argument values that will make the deduced A identical to
2719 // A. However, there are two cases that allow a difference:
2720 unsigned TDF = 0;
2721 // - If the original A is a reference type, A can be more
2722 // cv-qualified than the deduced A (i.e., the type referred to
2723 // by the reference)
2724 if (ToType->isReferenceType())
2725 TDF |= TDF_ParamWithReferenceType;
2726 // - The deduced A can be another pointer or pointer to member
2727 // type that can be converted to A via a qualification
2728 // conversion.
2729 //
2730 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2731 // both P and A are pointers or member pointers. In this case, we
2732 // just ignore cv-qualifiers completely).
2733 if ((P->isPointerType() && A->isPointerType()) ||
2734 (P->isMemberPointerType() && P->isMemberPointerType()))
2735 TDF |= TDF_IgnoreQualifiers;
2736 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002737 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002738 P, A, Info, Deduced, TDF))
2739 return Result;
2740
2741 // FIXME: we need to check that the deduced A is the same as A,
2742 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002744 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002745 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002746 FunctionDecl *Spec = 0;
2747 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002748 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2749 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002750 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2751 return Result;
2752}
2753
Douglas Gregor4b52e252009-12-21 23:17:24 +00002754/// \brief Deduce template arguments for a function template when there is
2755/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2756///
2757/// \param FunctionTemplate the function template for which we are performing
2758/// template argument deduction.
2759///
2760/// \param ExplicitTemplateArguments the explicitly-specified template
2761/// arguments.
2762///
2763/// \param Specialization if template argument deduction was successful,
2764/// this will be set to the function template specialization produced by
2765/// template argument deduction.
2766///
2767/// \param Info the argument will be updated to provide additional information
2768/// about template argument deduction.
2769///
2770/// \returns the result of template argument deduction.
2771Sema::TemplateDeductionResult
2772Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2773 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2774 FunctionDecl *&Specialization,
2775 TemplateDeductionInfo &Info) {
2776 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2777 QualType(), Specialization, Info);
2778}
2779
Douglas Gregor8a514912009-09-14 18:39:43 +00002780/// \brief Stores the result of comparing the qualifiers of two types.
2781enum DeductionQualifierComparison {
2782 NeitherMoreQualified = 0,
2783 ParamMoreQualified,
2784 ArgMoreQualified
2785};
2786
2787/// \brief Deduce the template arguments during partial ordering by comparing
2788/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2789///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002790/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002791///
2792/// \param TemplateParams the template parameters that we are deducing
2793///
2794/// \param ParamIn the parameter type
2795///
2796/// \param ArgIn the argument type
2797///
2798/// \param Info information about the template argument deduction itself
2799///
2800/// \param Deduced the deduced template arguments
2801///
2802/// \returns the result of template argument deduction so far. Note that a
2803/// "success" result means that template argument deduction has not yet failed,
2804/// but it may still fail, later, for other reasons.
2805static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002806DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002807 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002808 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002809 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002810 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2811 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002812 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2813 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002814
2815 // C++0x [temp.deduct.partial]p5:
2816 // Before the partial ordering is done, certain transformations are
2817 // performed on the types used for partial ordering:
2818 // - If P is a reference type, P is replaced by the type referred to.
2819 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002820 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002821 Param = ParamRef->getPointeeType();
2822
2823 // - If A is a reference type, A is replaced by the type referred to.
2824 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002825 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002826 Arg = ArgRef->getPointeeType();
2827
John McCalle27ec8a2009-10-23 23:03:21 +00002828 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002829 // C++0x [temp.deduct.partial]p6:
2830 // If both P and A were reference types (before being replaced with the
2831 // type referred to above), determine which of the two types (if any) is
2832 // more cv-qualified than the other; otherwise the types are considered to
2833 // be equally cv-qualified for partial ordering purposes. The result of this
2834 // determination will be used below.
2835 //
2836 // We save this information for later, using it only when deduction
2837 // succeeds in both directions.
2838 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2839 if (Param.isMoreQualifiedThan(Arg))
2840 QualifierResult = ParamMoreQualified;
2841 else if (Arg.isMoreQualifiedThan(Param))
2842 QualifierResult = ArgMoreQualified;
2843 QualifierComparisons->push_back(QualifierResult);
2844 }
2845
2846 // C++0x [temp.deduct.partial]p7:
2847 // Remove any top-level cv-qualifiers:
2848 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2849 // version of P.
2850 Param = Param.getUnqualifiedType();
2851 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2852 // version of A.
2853 Arg = Arg.getUnqualifiedType();
2854
2855 // C++0x [temp.deduct.partial]p8:
2856 // Using the resulting types P and A the deduction is then done as
2857 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2858 // from the argument template is considered to be at least as specialized
2859 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002860 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002861 Deduced, TDF_None);
2862}
2863
2864static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002865MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2866 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002867 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002868 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002869
2870/// \brief If this is a non-static member function,
2871static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2872 CXXMethodDecl *Method,
2873 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2874 if (Method->isStatic())
2875 return;
2876
2877 // C++ [over.match.funcs]p4:
2878 //
2879 // For non-static member functions, the type of the implicit
2880 // object parameter is
2881 // — "lvalue reference to cv X" for functions declared without a
2882 // ref-qualifier or with the & ref-qualifier
2883 // - "rvalue reference to cv X" for functions declared with the
2884 // && ref-qualifier
2885 //
2886 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2887 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2888 ArgTy = Context.getQualifiedType(ArgTy,
2889 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2890 ArgTy = Context.getLValueReferenceType(ArgTy);
2891 ArgTypes.push_back(ArgTy);
2892}
2893
Douglas Gregor8a514912009-09-14 18:39:43 +00002894/// \brief Determine whether the function template \p FT1 is at least as
2895/// specialized as \p FT2.
2896static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002897 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002898 FunctionTemplateDecl *FT1,
2899 FunctionTemplateDecl *FT2,
2900 TemplatePartialOrderingContext TPOC,
2901 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2902 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2903 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2904 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2905 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2906
2907 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2908 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002909 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002910 Deduced.resize(TemplateParams->size());
2911
2912 // C++0x [temp.deduct.partial]p3:
2913 // The types used to determine the ordering depend on the context in which
2914 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002915 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002916 CXXMethodDecl *Method1 = 0;
2917 CXXMethodDecl *Method2 = 0;
2918 bool IsNonStatic2 = false;
2919 bool IsNonStatic1 = false;
2920 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002921 switch (TPOC) {
2922 case TPOC_Call: {
2923 // - In the context of a function call, the function parameter types are
2924 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002925 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2926 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2927 IsNonStatic1 = Method1 && !Method1->isStatic();
2928 IsNonStatic2 = Method2 && !Method2->isStatic();
2929
2930 // C++0x [temp.func.order]p3:
2931 // [...] If only one of the function templates is a non-static
2932 // member, that function template is considered to have a new
2933 // first parameter inserted in its function parameter list. The
2934 // new parameter is of type "reference to cv A," where cv are
2935 // the cv-qualifiers of the function template (if any) and A is
2936 // the class of which the function template is a member.
2937 //
2938 // C++98/03 doesn't have this provision, so instead we drop the
2939 // first argument of the free function or static member, which
2940 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002941 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002942 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2943 IsNonStatic2 && !IsNonStatic1;
2944 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002945 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2946 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002947 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002948
2949 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002950 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2951 IsNonStatic1 && !IsNonStatic2;
2952 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002953 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2954 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002955 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002956
2957 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002958 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002959 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002960 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002961 Args2[I],
2962 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002963 Info,
2964 Deduced,
2965 QualifierComparisons))
2966 return false;
2967
2968 break;
2969 }
2970
2971 case TPOC_Conversion:
2972 // - In the context of a call to a conversion operator, the return types
2973 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002974 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002975 TemplateParams,
2976 Proto2->getResultType(),
2977 Proto1->getResultType(),
2978 Info,
2979 Deduced,
2980 QualifierComparisons))
2981 return false;
2982 break;
2983
2984 case TPOC_Other:
2985 // - In other contexts (14.6.6.2) the function template’s function type
2986 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002987 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002988 TemplateParams,
2989 FD2->getType(),
2990 FD1->getType(),
2991 Info,
2992 Deduced,
2993 QualifierComparisons))
2994 return false;
2995 break;
2996 }
2997
2998 // C++0x [temp.deduct.partial]p11:
2999 // In most cases, all template parameters must have values in order for
3000 // deduction to succeed, but for partial ordering purposes a template
3001 // parameter may remain without a value provided it is not used in the
3002 // types being used for partial ordering. [ Note: a template parameter used
3003 // in a non-deduced context is considered used. -end note]
3004 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3005 for (; ArgIdx != NumArgs; ++ArgIdx)
3006 if (Deduced[ArgIdx].isNull())
3007 break;
3008
3009 if (ArgIdx == NumArgs) {
3010 // All template arguments were deduced. FT1 is at least as specialized
3011 // as FT2.
3012 return true;
3013 }
3014
Douglas Gregore73bb602009-09-14 21:25:05 +00003015 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003016 llvm::SmallVector<bool, 4> UsedParameters;
3017 UsedParameters.resize(TemplateParams->size());
3018 switch (TPOC) {
3019 case TPOC_Call: {
3020 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003021 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3022 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3023 TemplateParams->getDepth(), UsedParameters);
3024 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003025 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3026 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003027 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003028 break;
3029 }
3030
3031 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003032 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3033 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003034 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003035 break;
3036
3037 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003038 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3039 TemplateParams->getDepth(),
3040 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003041 break;
3042 }
3043
3044 for (; ArgIdx != NumArgs; ++ArgIdx)
3045 // If this argument had no value deduced but was used in one of the types
3046 // used for partial ordering, then deduction fails.
3047 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3048 return false;
3049
3050 return true;
3051}
3052
3053
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003054/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003055/// to the rules of function template partial ordering (C++ [temp.func.order]).
3056///
3057/// \param FT1 the first function template
3058///
3059/// \param FT2 the second function template
3060///
Douglas Gregor8a514912009-09-14 18:39:43 +00003061/// \param TPOC the context in which we are performing partial ordering of
3062/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003063///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003064/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003065/// template is more specialized, returns NULL.
3066FunctionTemplateDecl *
3067Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3068 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003069 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003070 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003071 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003072 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3073 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003074 &QualifierComparisons);
3075
3076 if (Better1 != Better2) // We have a clear winner
3077 return Better1? FT1 : FT2;
3078
3079 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003080 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003081
3082
3083 // C++0x [temp.deduct.partial]p10:
3084 // If for each type being considered a given template is at least as
3085 // specialized for all types and more specialized for some set of types and
3086 // the other template is not more specialized for any types or is not at
3087 // least as specialized for any types, then the given template is more
3088 // specialized than the other template. Otherwise, neither template is more
3089 // specialized than the other.
3090 Better1 = false;
3091 Better2 = false;
3092 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3093 // C++0x [temp.deduct.partial]p9:
3094 // If, for a given type, deduction succeeds in both directions (i.e., the
3095 // types are identical after the transformations above) and if the type
3096 // from the argument template is more cv-qualified than the type from the
3097 // parameter template (as described above) that type is considered to be
3098 // more specialized than the other. If neither type is more cv-qualified
3099 // than the other then neither type is more specialized than the other.
3100 switch (QualifierComparisons[I]) {
3101 case NeitherMoreQualified:
3102 break;
3103
3104 case ParamMoreQualified:
3105 Better1 = true;
3106 if (Better2)
3107 return 0;
3108 break;
3109
3110 case ArgMoreQualified:
3111 Better2 = true;
3112 if (Better1)
3113 return 0;
3114 break;
3115 }
3116 }
3117
3118 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003119 if (Better1)
3120 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003121 else if (Better2)
3122 return FT2;
3123 else
3124 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003125}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003126
Douglas Gregord5a423b2009-09-25 18:43:00 +00003127/// \brief Determine if the two templates are equivalent.
3128static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3129 if (T1 == T2)
3130 return true;
3131
3132 if (!T1 || !T2)
3133 return false;
3134
3135 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3136}
3137
3138/// \brief Retrieve the most specialized of the given function template
3139/// specializations.
3140///
John McCallc373d482010-01-27 01:50:18 +00003141/// \param SpecBegin the start iterator of the function template
3142/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003143///
John McCallc373d482010-01-27 01:50:18 +00003144/// \param SpecEnd the end iterator of the function template
3145/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003146///
3147/// \param TPOC the partial ordering context to use to compare the function
3148/// template specializations.
3149///
3150/// \param Loc the location where the ambiguity or no-specializations
3151/// diagnostic should occur.
3152///
3153/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3154/// no matching candidates.
3155///
3156/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3157/// occurs.
3158///
3159/// \param CandidateDiag partial diagnostic used for each function template
3160/// specialization that is a candidate in the ambiguous ordering. One parameter
3161/// in this diagnostic should be unbound, which will correspond to the string
3162/// describing the template arguments for the function template specialization.
3163///
3164/// \param Index if non-NULL and the result of this function is non-nULL,
3165/// receives the index corresponding to the resulting function template
3166/// specialization.
3167///
3168/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003169/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003170///
3171/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3172/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003173UnresolvedSetIterator
3174Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3175 UnresolvedSetIterator SpecEnd,
3176 TemplatePartialOrderingContext TPOC,
3177 SourceLocation Loc,
3178 const PartialDiagnostic &NoneDiag,
3179 const PartialDiagnostic &AmbigDiag,
3180 const PartialDiagnostic &CandidateDiag) {
3181 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003182 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003183 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003184 }
3185
John McCallc373d482010-01-27 01:50:18 +00003186 if (SpecBegin + 1 == SpecEnd)
3187 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003188
3189 // Find the function template that is better than all of the templates it
3190 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003191 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003192 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003193 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003194 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003195 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3196 FunctionTemplateDecl *Challenger
3197 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003198 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003199 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003200 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003201 Challenger)) {
3202 Best = I;
3203 BestTemplate = Challenger;
3204 }
3205 }
3206
3207 // Make sure that the "best" function template is more specialized than all
3208 // of the others.
3209 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003210 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3211 FunctionTemplateDecl *Challenger
3212 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003213 if (I != Best &&
3214 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003215 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003216 BestTemplate)) {
3217 Ambiguous = true;
3218 break;
3219 }
3220 }
3221
3222 if (!Ambiguous) {
3223 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003224 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003225 }
3226
3227 // Diagnose the ambiguity.
3228 Diag(Loc, AmbigDiag);
3229
3230 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003231 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3232 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003233 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003234 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3235 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003236
John McCallc373d482010-01-27 01:50:18 +00003237 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003238}
3239
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003240/// \brief Returns the more specialized class template partial specialization
3241/// according to the rules of partial ordering of class template partial
3242/// specializations (C++ [temp.class.order]).
3243///
3244/// \param PS1 the first class template partial specialization
3245///
3246/// \param PS2 the second class template partial specialization
3247///
3248/// \returns the more specialized class template partial specialization. If
3249/// neither partial specialization is more specialized, returns NULL.
3250ClassTemplatePartialSpecializationDecl *
3251Sema::getMoreSpecializedPartialSpecialization(
3252 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003253 ClassTemplatePartialSpecializationDecl *PS2,
3254 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003255 // C++ [temp.class.order]p1:
3256 // For two class template partial specializations, the first is at least as
3257 // specialized as the second if, given the following rewrite to two
3258 // function templates, the first function template is at least as
3259 // specialized as the second according to the ordering rules for function
3260 // templates (14.6.6.2):
3261 // - the first function template has the same template parameters as the
3262 // first partial specialization and has a single function parameter
3263 // whose type is a class template specialization with the template
3264 // arguments of the first partial specialization, and
3265 // - the second function template has the same template parameters as the
3266 // second partial specialization and has a single function parameter
3267 // whose type is a class template specialization with the template
3268 // arguments of the second partial specialization.
3269 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003270 // Rather than synthesize function templates, we merely perform the
3271 // equivalent partial ordering by performing deduction directly on
3272 // the template arguments of the class template partial
3273 // specializations. This computation is slightly simpler than the
3274 // general problem of function template partial ordering, because
3275 // class template partial specializations are more constrained. We
3276 // know that every template parameter is deducible from the class
3277 // template partial specialization's template arguments, for
3278 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003279 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003280 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003281
3282 QualType PT1 = PS1->getInjectedSpecializationType();
3283 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003284
3285 // Determine whether PS1 is at least as specialized as PS2
3286 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003287 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003288 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003289 PT2,
3290 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003291 Info,
3292 Deduced,
3293 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003294 if (Better1) {
3295 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3296 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003297 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3298 PS1->getTemplateArgs(),
3299 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003300 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003301
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003302 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003303 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003304 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003305 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003306 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003307 PT1,
3308 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003309 Info,
3310 Deduced,
3311 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003312 if (Better2) {
3313 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3314 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003315 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3316 PS2->getTemplateArgs(),
3317 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003318 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003319
3320 if (Better1 == Better2)
3321 return 0;
3322
3323 return Better1? PS1 : PS2;
3324}
3325
Mike Stump1eb44332009-09-09 15:08:12 +00003326static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003327MarkUsedTemplateParameters(Sema &SemaRef,
3328 const TemplateArgument &TemplateArg,
3329 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003330 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003331 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003332
Douglas Gregore73bb602009-09-14 21:25:05 +00003333/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003334/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003335static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003336MarkUsedTemplateParameters(Sema &SemaRef,
3337 const Expr *E,
3338 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003339 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003340 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003341 // We can deduce from a pack expansion.
3342 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3343 E = Expansion->getPattern();
3344
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003345 // Skip through any implicit casts we added while type-checking.
3346 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3347 E = ICE->getSubExpr();
3348
Douglas Gregore73bb602009-09-14 21:25:05 +00003349 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3350 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003351 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003352 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003353 return;
3354
Mike Stump1eb44332009-09-09 15:08:12 +00003355 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003356 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3357 if (!NTTP)
3358 return;
3359
Douglas Gregored9c0f92009-10-29 00:04:11 +00003360 if (NTTP->getDepth() == Depth)
3361 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003362}
3363
Douglas Gregore73bb602009-09-14 21:25:05 +00003364/// \brief Mark the template parameters that are used by the given
3365/// nested name specifier.
3366static void
3367MarkUsedTemplateParameters(Sema &SemaRef,
3368 NestedNameSpecifier *NNS,
3369 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003370 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003371 llvm::SmallVectorImpl<bool> &Used) {
3372 if (!NNS)
3373 return;
3374
Douglas Gregored9c0f92009-10-29 00:04:11 +00003375 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3376 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003377 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003378 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003379}
3380
3381/// \brief Mark the template parameters that are used by the given
3382/// template name.
3383static void
3384MarkUsedTemplateParameters(Sema &SemaRef,
3385 TemplateName Name,
3386 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003387 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003388 llvm::SmallVectorImpl<bool> &Used) {
3389 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3390 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003391 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3392 if (TTP->getDepth() == Depth)
3393 Used[TTP->getIndex()] = true;
3394 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003395 return;
3396 }
3397
Douglas Gregor788cd062009-11-11 01:00:40 +00003398 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3399 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3400 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003401 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003402 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3403 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003404}
3405
3406/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003407/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003408static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003409MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3410 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003411 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003412 llvm::SmallVectorImpl<bool> &Used) {
3413 if (T.isNull())
3414 return;
3415
Douglas Gregor031a5882009-06-13 00:26:55 +00003416 // Non-dependent types have nothing deducible
3417 if (!T->isDependentType())
3418 return;
3419
3420 T = SemaRef.Context.getCanonicalType(T);
3421 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003422 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003423 MarkUsedTemplateParameters(SemaRef,
3424 cast<PointerType>(T)->getPointeeType(),
3425 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003426 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003427 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003428 break;
3429
3430 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003431 MarkUsedTemplateParameters(SemaRef,
3432 cast<BlockPointerType>(T)->getPointeeType(),
3433 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003434 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003435 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003436 break;
3437
3438 case Type::LValueReference:
3439 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003440 MarkUsedTemplateParameters(SemaRef,
3441 cast<ReferenceType>(T)->getPointeeType(),
3442 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003443 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003444 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003445 break;
3446
3447 case Type::MemberPointer: {
3448 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003449 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003450 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003451 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003452 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003453 break;
3454 }
3455
3456 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003457 MarkUsedTemplateParameters(SemaRef,
3458 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003459 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003460 // Fall through to check the element type
3461
3462 case Type::ConstantArray:
3463 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003464 MarkUsedTemplateParameters(SemaRef,
3465 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003466 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003467 break;
3468
3469 case Type::Vector:
3470 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003471 MarkUsedTemplateParameters(SemaRef,
3472 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003473 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003474 break;
3475
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003476 case Type::DependentSizedExtVector: {
3477 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003478 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003479 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003480 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003481 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003482 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003483 break;
3484 }
3485
Douglas Gregor031a5882009-06-13 00:26:55 +00003486 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003487 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003489 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003490 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003491 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003492 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003493 break;
3494 }
3495
Douglas Gregored9c0f92009-10-29 00:04:11 +00003496 case Type::TemplateTypeParm: {
3497 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3498 if (TTP->getDepth() == Depth)
3499 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003500 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003501 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003502
John McCall31f17ec2010-04-27 00:57:59 +00003503 case Type::InjectedClassName:
3504 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3505 // fall through
3506
Douglas Gregor031a5882009-06-13 00:26:55 +00003507 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003508 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003509 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003510 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003511 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003512
3513 // C++0x [temp.deduct.type]p9:
3514 // If the template argument list of P contains a pack expansion that is not
3515 // the last template argument, the entire template argument list is a
3516 // non-deduced context.
3517 if (OnlyDeduced &&
3518 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3519 break;
3520
Douglas Gregore73bb602009-09-14 21:25:05 +00003521 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003522 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3523 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003524 break;
3525 }
3526
Douglas Gregore73bb602009-09-14 21:25:05 +00003527 case Type::Complex:
3528 if (!OnlyDeduced)
3529 MarkUsedTemplateParameters(SemaRef,
3530 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003531 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003532 break;
3533
Douglas Gregor4714c122010-03-31 17:34:00 +00003534 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003535 if (!OnlyDeduced)
3536 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003537 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003538 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003539 break;
3540
John McCall33500952010-06-11 00:33:02 +00003541 case Type::DependentTemplateSpecialization: {
3542 const DependentTemplateSpecializationType *Spec
3543 = cast<DependentTemplateSpecializationType>(T);
3544 if (!OnlyDeduced)
3545 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3546 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003547
3548 // C++0x [temp.deduct.type]p9:
3549 // If the template argument list of P contains a pack expansion that is not
3550 // the last template argument, the entire template argument list is a
3551 // non-deduced context.
3552 if (OnlyDeduced &&
3553 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3554 break;
3555
John McCall33500952010-06-11 00:33:02 +00003556 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3557 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3558 Used);
3559 break;
3560 }
3561
John McCallad5e7382010-03-01 23:49:17 +00003562 case Type::TypeOf:
3563 if (!OnlyDeduced)
3564 MarkUsedTemplateParameters(SemaRef,
3565 cast<TypeOfType>(T)->getUnderlyingType(),
3566 OnlyDeduced, Depth, Used);
3567 break;
3568
3569 case Type::TypeOfExpr:
3570 if (!OnlyDeduced)
3571 MarkUsedTemplateParameters(SemaRef,
3572 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3573 OnlyDeduced, Depth, Used);
3574 break;
3575
3576 case Type::Decltype:
3577 if (!OnlyDeduced)
3578 MarkUsedTemplateParameters(SemaRef,
3579 cast<DecltypeType>(T)->getUnderlyingExpr(),
3580 OnlyDeduced, Depth, Used);
3581 break;
3582
Douglas Gregor7536dd52010-12-20 02:24:11 +00003583 case Type::PackExpansion:
3584 MarkUsedTemplateParameters(SemaRef,
3585 cast<PackExpansionType>(T)->getPattern(),
3586 OnlyDeduced, Depth, Used);
3587 break;
3588
Douglas Gregore73bb602009-09-14 21:25:05 +00003589 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003590 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003591 case Type::VariableArray:
3592 case Type::FunctionNoProto:
3593 case Type::Record:
3594 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003595 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003596 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003597 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003598 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003599#define TYPE(Class, Base)
3600#define ABSTRACT_TYPE(Class, Base)
3601#define DEPENDENT_TYPE(Class, Base)
3602#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3603#include "clang/AST/TypeNodes.def"
3604 break;
3605 }
3606}
3607
Douglas Gregore73bb602009-09-14 21:25:05 +00003608/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003609/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003610static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003611MarkUsedTemplateParameters(Sema &SemaRef,
3612 const TemplateArgument &TemplateArg,
3613 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003614 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003615 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003616 switch (TemplateArg.getKind()) {
3617 case TemplateArgument::Null:
3618 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003619 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003620 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Douglas Gregor031a5882009-06-13 00:26:55 +00003622 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003623 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003624 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003625 break;
3626
Douglas Gregor788cd062009-11-11 01:00:40 +00003627 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003628 case TemplateArgument::TemplateExpansion:
3629 MarkUsedTemplateParameters(SemaRef,
3630 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003631 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003632 break;
3633
3634 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003635 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003636 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003637 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003638
Anders Carlssond01b1da2009-06-15 17:04:53 +00003639 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003640 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3641 PEnd = TemplateArg.pack_end();
3642 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003643 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003644 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003645 }
3646}
3647
3648/// \brief Mark the template parameters can be deduced by the given
3649/// template argument list.
3650///
3651/// \param TemplateArgs the template argument list from which template
3652/// parameters will be deduced.
3653///
3654/// \param Deduced a bit vector whose elements will be set to \c true
3655/// to indicate when the corresponding template parameter will be
3656/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003657void
Douglas Gregore73bb602009-09-14 21:25:05 +00003658Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003659 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003660 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003661 // C++0x [temp.deduct.type]p9:
3662 // If the template argument list of P contains a pack expansion that is not
3663 // the last template argument, the entire template argument list is a
3664 // non-deduced context.
3665 if (OnlyDeduced &&
3666 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3667 return;
3668
Douglas Gregor031a5882009-06-13 00:26:55 +00003669 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003670 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3671 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003672}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003673
3674/// \brief Marks all of the template parameters that will be deduced by a
3675/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003676void
3677Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3678 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003679 TemplateParameterList *TemplateParams
3680 = FunctionTemplate->getTemplateParameters();
3681 Deduced.clear();
3682 Deduced.resize(TemplateParams->size());
3683
3684 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3685 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3686 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003687 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003688}