blob: 5837ebd8e541ff636386bab8f7a00c54712925a9 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument *Params, unsigned NumParams,
91 const TemplateArgument *Args, unsigned NumArgs,
92 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000093 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +000095
Douglas Gregor199d9912009-06-05 00:53:49 +000096/// \brief If the given expression is of a form that permits the deduction
97/// of a non-type template parameter, return the declaration of that
98/// non-type template parameter.
99static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
100 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
101 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Douglas Gregor199d9912009-06-05 00:53:49 +0000103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
104 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Douglas Gregor199d9912009-06-05 00:53:49 +0000106 return 0;
107}
108
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000109/// \brief Determine whether two declaration pointers refer to the same
110/// declaration.
111static bool isSameDeclaration(Decl *X, Decl *Y) {
112 if (!X || !Y)
113 return !X && !Y;
114
115 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
116 X = NX->getUnderlyingDecl();
117 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
118 Y = NY->getUnderlyingDecl();
119
120 return X->getCanonicalDecl() == Y->getCanonicalDecl();
121}
122
123/// \brief Verify that the given, deduced template arguments are compatible.
124///
125/// \returns The deduced template argument, or a NULL template argument if
126/// the deduced template arguments were incompatible.
127static DeducedTemplateArgument
128checkDeducedTemplateArguments(ASTContext &Context,
129 const DeducedTemplateArgument &X,
130 const DeducedTemplateArgument &Y) {
131 // We have no deduction for one or both of the arguments; they're compatible.
132 if (X.isNull())
133 return Y;
134 if (Y.isNull())
135 return X;
136
137 switch (X.getKind()) {
138 case TemplateArgument::Null:
139 llvm_unreachable("Non-deduced template arguments handled above");
140
141 case TemplateArgument::Type:
142 // If two template type arguments have the same type, they're compatible.
143 if (Y.getKind() == TemplateArgument::Type &&
144 Context.hasSameType(X.getAsType(), Y.getAsType()))
145 return X;
146
147 return DeducedTemplateArgument();
148
149 case TemplateArgument::Integral:
150 // If we deduced a constant in one case and either a dependent expression or
151 // declaration in another case, keep the integral constant.
152 // If both are integral constants with the same value, keep that value.
153 if (Y.getKind() == TemplateArgument::Expression ||
154 Y.getKind() == TemplateArgument::Declaration ||
155 (Y.getKind() == TemplateArgument::Integral &&
156 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
157 return DeducedTemplateArgument(X,
158 X.wasDeducedFromArrayBound() &&
159 Y.wasDeducedFromArrayBound());
160
161 // All other combinations are incompatible.
162 return DeducedTemplateArgument();
163
164 case TemplateArgument::Template:
165 if (Y.getKind() == TemplateArgument::Template &&
166 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
167 return X;
168
169 // All other combinations are incompatible.
170 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000171
172 case TemplateArgument::TemplateExpansion:
173 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
174 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
175 Y.getAsTemplateOrTemplatePattern()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
180
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000181 case TemplateArgument::Expression:
182 // If we deduced a dependent expression in one case and either an integral
183 // constant or a declaration in another case, keep the integral constant
184 // or declaration.
185 if (Y.getKind() == TemplateArgument::Integral ||
186 Y.getKind() == TemplateArgument::Declaration)
187 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
188 Y.wasDeducedFromArrayBound());
189
190 if (Y.getKind() == TemplateArgument::Expression) {
191 // Compare the expressions for equality
192 llvm::FoldingSetNodeID ID1, ID2;
193 X.getAsExpr()->Profile(ID1, Context, true);
194 Y.getAsExpr()->Profile(ID2, Context, true);
195 if (ID1 == ID2)
196 return X;
197 }
198
199 // All other combinations are incompatible.
200 return DeducedTemplateArgument();
201
202 case TemplateArgument::Declaration:
203 // If we deduced a declaration and a dependent expression, keep the
204 // declaration.
205 if (Y.getKind() == TemplateArgument::Expression)
206 return X;
207
208 // If we deduced a declaration and an integral constant, keep the
209 // integral constant.
210 if (Y.getKind() == TemplateArgument::Integral)
211 return Y;
212
213 // If we deduced two declarations, make sure they they refer to the
214 // same declaration.
215 if (Y.getKind() == TemplateArgument::Declaration &&
216 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
217 return X;
218
219 // All other combinations are incompatible.
220 return DeducedTemplateArgument();
221
222 case TemplateArgument::Pack:
223 if (Y.getKind() != TemplateArgument::Pack ||
224 X.pack_size() != Y.pack_size())
225 return DeducedTemplateArgument();
226
227 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
228 XAEnd = X.pack_end(),
229 YA = Y.pack_begin();
230 XA != XAEnd; ++XA, ++YA) {
231 // FIXME: We've lost the "deduced from array bound" bit.
232 if (checkDeducedTemplateArguments(Context, *XA, *YA).isNull())
233 return DeducedTemplateArgument();
234 }
235
236 return X;
237 }
238
239 return DeducedTemplateArgument();
240}
241
Mike Stump1eb44332009-09-09 15:08:12 +0000242/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000243/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000244static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000245DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000246 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000247 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000248 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000249 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000250 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000251 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000252 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000254 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
255 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
256 Deduced[NTTP->getIndex()],
257 NewDeduced);
258 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000259 Info.Param = NTTP;
260 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000261 Info.SecondArg = NewDeduced;
262 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000263 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000264
265 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000266 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000267}
268
Mike Stump1eb44332009-09-09 15:08:12 +0000269/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000270/// from the given type- or value-dependent expression.
271///
272/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000273static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000274DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000275 NonTypeTemplateParmDecl *NTTP,
276 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000277 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000278 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000279 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000280 "Cannot deduce non-type template argument with depth > 0");
281 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
282 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000284 DeducedTemplateArgument NewDeduced(Value);
285 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
286 Deduced[NTTP->getIndex()],
287 NewDeduced);
288
289 if (Result.isNull()) {
290 Info.Param = NTTP;
291 Info.FirstArg = Deduced[NTTP->getIndex()];
292 Info.SecondArg = NewDeduced;
293 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000294 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295
296 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000297 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000298}
299
Douglas Gregor15755cb2009-11-13 23:45:44 +0000300/// \brief Deduce the value of the given non-type template parameter
301/// from the given declaration.
302///
303/// \returns true if deduction succeeded, false otherwise.
304static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000305DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000306 NonTypeTemplateParmDecl *NTTP,
307 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000308 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000309 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000310 assert(NTTP->getDepth() == 0 &&
311 "Cannot deduce non-type template argument with depth > 0");
312
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000313 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
314 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
315 Deduced[NTTP->getIndex()],
316 NewDeduced);
317 if (Result.isNull()) {
318 Info.Param = NTTP;
319 Info.FirstArg = Deduced[NTTP->getIndex()];
320 Info.SecondArg = NewDeduced;
321 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000322 }
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000325 return Sema::TDK_Success;
326}
327
Douglas Gregorf67875d2009-06-12 18:26:56 +0000328static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000329DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000330 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000331 TemplateName Param,
332 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000333 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000334 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000335 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000336 if (!ParamDecl) {
337 // The parameter type is dependent and is not a template template parameter,
338 // so there is nothing that we can deduce.
339 return Sema::TDK_Success;
340 }
341
342 if (TemplateTemplateParmDecl *TempParam
343 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000344 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
345 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
346 Deduced[TempParam->getIndex()],
347 NewDeduced);
348 if (Result.isNull()) {
349 Info.Param = TempParam;
350 Info.FirstArg = Deduced[TempParam->getIndex()];
351 Info.SecondArg = NewDeduced;
352 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000353 }
354
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 Deduced[TempParam->getIndex()] = Result;
356 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000357 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000358
359 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000360 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000361 return Sema::TDK_Success;
362
363 // Mismatch of non-dependent template parameter to argument.
364 Info.FirstArg = TemplateArgument(Param);
365 Info.SecondArg = TemplateArgument(Arg);
366 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000367}
368
Mike Stump1eb44332009-09-09 15:08:12 +0000369/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000370/// type (which is a template-id) with the template argument type.
371///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000372/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000373///
374/// \param TemplateParams the template parameters that we are deducing
375///
376/// \param Param the parameter type
377///
378/// \param Arg the argument type
379///
380/// \param Info information about the template argument deduction itself
381///
382/// \param Deduced the deduced template arguments
383///
384/// \returns the result of template argument deduction so far. Note that a
385/// "success" result means that template argument deduction has not yet failed,
386/// but it may still fail, later, for other reasons.
387static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000388DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000389 TemplateParameterList *TemplateParams,
390 const TemplateSpecializationType *Param,
391 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000392 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000393 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000394 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000396 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000397 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000398 = dyn_cast<TemplateSpecializationType>(Arg)) {
399 // Perform template argument deduction for the template name.
400 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000401 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000402 Param->getTemplateName(),
403 SpecArg->getTemplateName(),
404 Info, Deduced))
405 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000408 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000409 // argument. Ignore any missing/extra arguments, since they could be
410 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000411 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000412 Param->getArgs(), Param->getNumArgs(),
413 SpecArg->getArgs(), SpecArg->getNumArgs(),
414 Info, Deduced,
415 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000418 // If the argument type is a class template specialization, we
419 // perform template argument deduction using its template
420 // arguments.
421 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
422 if (!RecordArg)
423 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
425 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000426 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
427 if (!SpecArg)
428 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000430 // Perform template argument deduction for the template name.
431 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000432 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000433 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000434 Param->getTemplateName(),
435 TemplateName(SpecArg->getSpecializedTemplate()),
436 Info, Deduced))
437 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor20a55e22010-12-22 18:17:10 +0000439 // Perform template argument deduction for the template arguments.
440 return DeduceTemplateArguments(S, TemplateParams,
441 Param->getArgs(), Param->getNumArgs(),
442 SpecArg->getTemplateArgs().data(),
443 SpecArg->getTemplateArgs().size(),
444 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445}
446
John McCallcd05e812010-08-28 22:14:41 +0000447/// \brief Determines whether the given type is an opaque type that
448/// might be more qualified when instantiated.
449static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
450 switch (T->getTypeClass()) {
451 case Type::TypeOfExpr:
452 case Type::TypeOf:
453 case Type::DependentName:
454 case Type::Decltype:
455 case Type::UnresolvedUsing:
456 return true;
457
458 case Type::ConstantArray:
459 case Type::IncompleteArray:
460 case Type::VariableArray:
461 case Type::DependentSizedArray:
462 return IsPossiblyOpaquelyQualifiedType(
463 cast<ArrayType>(T)->getElementType());
464
465 default:
466 return false;
467 }
468}
469
Douglas Gregor500d3312009-06-26 18:27:22 +0000470/// \brief Deduce the template arguments by comparing the parameter type and
471/// the argument type (C++ [temp.deduct.type]).
472///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000473/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000474///
475/// \param TemplateParams the template parameters that we are deducing
476///
477/// \param ParamIn the parameter type
478///
479/// \param ArgIn the argument type
480///
481/// \param Info information about the template argument deduction itself
482///
483/// \param Deduced the deduced template arguments
484///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000485/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000486/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000487///
488/// \returns the result of template argument deduction so far. Note that a
489/// "success" result means that template argument deduction has not yet failed,
490/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000491static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000492DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000493 TemplateParameterList *TemplateParams,
494 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000495 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000496 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000497 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000498 // We only want to look at the canonical types, since typedefs and
499 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000500 QualType Param = S.Context.getCanonicalType(ParamIn);
501 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000502
Douglas Gregor500d3312009-06-26 18:27:22 +0000503 // C++0x [temp.deduct.call]p4 bullet 1:
504 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000505 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000506 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000507 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000508 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000509 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000510 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
511 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000512 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000515 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000516 if (!Param->isDependentType()) {
517 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
518
519 return Sema::TDK_NonDeducedMismatch;
520 }
521
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000522 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000523 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000524
Douglas Gregor199d9912009-06-05 00:53:49 +0000525 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000526 // A template type argument T, a template template argument TT or a
527 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000528 // the following forms:
529 //
530 // T
531 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000532 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000533 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000534 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000535 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000537 // If the argument type is an array type, move the qualifiers up to the
538 // top level, so they can be matched with the qualifiers on the parameter.
539 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000540 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000541 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000542 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000543 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000544 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000545 RecanonicalizeArg = true;
546 }
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000549 // The argument type can not be less qualified than the parameter
550 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000551 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000552 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000553 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000554 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000555 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000556 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000557
558 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000559 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000560 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000561
562 // local manipulation is okay because it's canonical
563 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000564 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000565 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000567 DeducedTemplateArgument NewDeduced(DeducedType);
568 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
569 Deduced[Index],
570 NewDeduced);
571 if (Result.isNull()) {
572 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
573 Info.FirstArg = Deduced[Index];
574 Info.SecondArg = NewDeduced;
575 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000576 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000577
578 Deduced[Index] = Result;
579 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000580 }
581
Douglas Gregorf67875d2009-06-12 18:26:56 +0000582 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000583 Info.FirstArg = TemplateArgument(ParamIn);
584 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000585
Douglas Gregor508f1c82009-06-26 23:10:12 +0000586 // Check the cv-qualifiers on the parameter and argument types.
587 if (!(TDF & TDF_IgnoreQualifiers)) {
588 if (TDF & TDF_ParamWithReferenceType) {
589 if (Param.isMoreQualifiedThan(Arg))
590 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000591 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000592 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000593 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000594 }
595 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000596
Douglas Gregord560d502009-06-04 00:21:18 +0000597 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000598 // No deduction possible for these types
599 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000600 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregor199d9912009-06-05 00:53:49 +0000602 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000603 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000604 QualType PointeeType;
605 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
606 PointeeType = PointerArg->getPointeeType();
607 } else if (const ObjCObjectPointerType *PointerArg
608 = Arg->getAs<ObjCObjectPointerType>()) {
609 PointeeType = PointerArg->getPointeeType();
610 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000611 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor41128772009-06-26 23:27:24 +0000614 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000615 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000616 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000617 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000618 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Douglas Gregor199d9912009-06-05 00:53:49 +0000621 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000622 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000623 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000624 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000625 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000627 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000628 cast<LValueReferenceType>(Param)->getPointeeType(),
629 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000630 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000631 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000632
Douglas Gregor199d9912009-06-05 00:53:49 +0000633 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000634 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000635 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000636 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000637 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000639 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000640 cast<RValueReferenceType>(Param)->getPointeeType(),
641 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000642 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Douglas Gregor199d9912009-06-05 00:53:49 +0000645 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000646 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000647 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000648 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000649 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000650 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000651
John McCalle4f26e52010-08-19 00:20:19 +0000652 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000653 return DeduceTemplateArguments(S, TemplateParams,
654 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000655 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000656 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000657 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000658
659 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000660 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000661 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000662 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000663 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000664 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000665
666 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000667 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000668 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000669 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000670
John McCalle4f26e52010-08-19 00:20:19 +0000671 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000672 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000673 ConstantArrayParm->getElementType(),
674 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000675 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000676 }
677
Douglas Gregor199d9912009-06-05 00:53:49 +0000678 // type [i]
679 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000680 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000681 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000682 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
John McCalle4f26e52010-08-19 00:20:19 +0000684 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
685
Douglas Gregor199d9912009-06-05 00:53:49 +0000686 // Check the element type of the arrays
687 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000688 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000689 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000690 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000691 DependentArrayParm->getElementType(),
692 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000693 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000694 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregor199d9912009-06-05 00:53:49 +0000696 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000697 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000698 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
699 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000700 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000701
702 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000703 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000704 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000705 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000706 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000707 = dyn_cast<ConstantArrayType>(ArrayArg)) {
708 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000709 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
710 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000711 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000712 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000713 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000714 if (const DependentSizedArrayType *DependentArrayArg
715 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000716 if (DependentArrayArg->getSizeExpr())
717 return DeduceNonTypeTemplateArgument(S, NTTP,
718 DependentArrayArg->getSizeExpr(),
719 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Douglas Gregor199d9912009-06-05 00:53:49 +0000721 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000722 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000723 }
Mike Stump1eb44332009-09-09 15:08:12 +0000724
725 // type(*)(T)
726 // T(*)()
727 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000728 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000729 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000730 dyn_cast<FunctionProtoType>(Arg);
731 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000732 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
734 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000735 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000736
Mike Stump1eb44332009-09-09 15:08:12 +0000737 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000738 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000739 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000741 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000742 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000744 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000745 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000746
Anders Carlssona27fad52009-06-08 15:19:08 +0000747 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000748 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000749 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000750 FunctionProtoParam->getResultType(),
751 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000752 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000753 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlssona27fad52009-06-08 15:19:08 +0000755 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
756 // Check argument types.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000757 // FIXME: Variadic templates.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000758 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000759 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000760 FunctionProtoParam->getArgType(I),
761 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000762 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000763 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregorf67875d2009-06-12 18:26:56 +0000766 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
John McCall3cb0ebd2010-03-10 03:28:59 +0000769 case Type::InjectedClassName: {
770 // Treat a template's injected-class-name as if the template
771 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000772 Param = cast<InjectedClassNameType>(Param)
773 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000774 assert(isa<TemplateSpecializationType>(Param) &&
775 "injected class name is not a template specialization type");
776 // fall through
777 }
778
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000779 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000780 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000781 // TT<T>
782 // TT<i>
783 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000784 case Type::TemplateSpecialization: {
785 const TemplateSpecializationType *SpecParam
786 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000788 // Try to deduce template arguments from the template-id.
789 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000790 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000791 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000793 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000794 // C++ [temp.deduct.call]p3b3:
795 // If P is a class, and P has the form template-id, then A can be a
796 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000797 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000798 // class pointed to by the deduced A.
799 //
800 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000801 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000802 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000803 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
804 // We cannot inspect base classes as part of deduction when the type
805 // is incomplete, so either instantiate any templates necessary to
806 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000807 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000808 return Result;
809
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000810 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000811 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000812 // ToVisit is our stack of records that we still need to visit.
813 llvm::SmallPtrSet<const RecordType *, 8> Visited;
814 llvm::SmallVector<const RecordType *, 8> ToVisit;
815 ToVisit.push_back(RecordT);
816 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000817 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
818 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000819 while (!ToVisit.empty()) {
820 // Retrieve the next class in the inheritance hierarchy.
821 const RecordType *NextT = ToVisit.back();
822 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000824 // If we have already seen this type, skip it.
825 if (!Visited.insert(NextT))
826 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000828 // If this is a base class, try to perform template argument
829 // deduction from it.
830 if (NextT != RecordT) {
831 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000832 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000833 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000835 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000836 // note that we had some success. Otherwise, ignore any deductions
837 // from this base class.
838 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000839 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000840 DeducedOrig = Deduced;
841 }
842 else
843 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000846 // Visit base classes
847 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
848 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
849 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000850 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000851 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000852 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000853 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000854 }
855 }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000857 if (Successful)
858 return Sema::TDK_Success;
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000863 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000864 }
865
Douglas Gregor637a4092009-06-10 23:47:09 +0000866 // T type::*
867 // T T::*
868 // T (type::*)()
869 // type (T::*)()
870 // type (type::*)(T)
871 // type (T::*)(T)
872 // T (type::*)(T)
873 // T (T::*)()
874 // T (T::*)(T)
875 case Type::MemberPointer: {
876 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
877 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
878 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000879 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000880
Douglas Gregorf67875d2009-06-12 18:26:56 +0000881 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000882 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000883 MemPtrParam->getPointeeType(),
884 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000885 Info, Deduced,
886 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000887 return Result;
888
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000889 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000890 QualType(MemPtrParam->getClass(), 0),
891 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000892 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000893 }
894
Anders Carlsson9a917e42009-06-12 22:56:54 +0000895 // (clang extension)
896 //
Mike Stump1eb44332009-09-09 15:08:12 +0000897 // type(^)(T)
898 // T(^)()
899 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000900 case Type::BlockPointer: {
901 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
902 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Anders Carlsson859ba502009-06-12 16:23:10 +0000904 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000905 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000907 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000908 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000909 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000910 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000911 }
912
Douglas Gregor637a4092009-06-10 23:47:09 +0000913 case Type::TypeOfExpr:
914 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000915 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000916 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000917 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000918
Douglas Gregord560d502009-06-04 00:21:18 +0000919 default:
920 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000921 }
922
923 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000924 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000925}
926
Douglas Gregorf67875d2009-06-12 18:26:56 +0000927static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000928DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000929 TemplateParameterList *TemplateParams,
930 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000931 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000932 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000933 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000934 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000935 case TemplateArgument::Null:
936 assert(false && "Null template argument in parameter list");
937 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
939 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000940 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000941 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000942 Arg.getAsType(), Info, Deduced, 0);
943 Info.FirstArg = Param;
944 Info.SecondArg = Arg;
945 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +0000946
Douglas Gregor788cd062009-11-11 01:00:40 +0000947 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000948 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000949 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000950 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000951 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000952 Info.FirstArg = Param;
953 Info.SecondArg = Arg;
954 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +0000955
956 case TemplateArgument::TemplateExpansion:
957 llvm_unreachable("caller should handle pack expansions");
958 break;
Douglas Gregor788cd062009-11-11 01:00:40 +0000959
Douglas Gregor199d9912009-06-05 00:53:49 +0000960 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000961 if (Arg.getKind() == TemplateArgument::Declaration &&
962 Param.getAsDecl()->getCanonicalDecl() ==
963 Arg.getAsDecl()->getCanonicalDecl())
964 return Sema::TDK_Success;
965
Douglas Gregorf67875d2009-06-12 18:26:56 +0000966 Info.FirstArg = Param;
967 Info.SecondArg = Arg;
968 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor199d9912009-06-05 00:53:49 +0000970 case TemplateArgument::Integral:
971 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000972 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000973 return Sema::TDK_Success;
974
975 Info.FirstArg = Param;
976 Info.SecondArg = Arg;
977 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000978 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000979
980 if (Arg.getKind() == TemplateArgument::Expression) {
981 Info.FirstArg = Param;
982 Info.SecondArg = Arg;
983 return Sema::TDK_NonDeducedMismatch;
984 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000985
Douglas Gregorf67875d2009-06-12 18:26:56 +0000986 Info.FirstArg = Param;
987 Info.SecondArg = Arg;
988 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Douglas Gregor199d9912009-06-05 00:53:49 +0000990 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000991 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000992 = getDeducedParameterFromExpr(Param.getAsExpr())) {
993 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000994 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000995 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000996 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000997 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000998 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000999 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001000 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001001 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001002 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001003 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001004 Info, Deduced);
1005
Douglas Gregorf67875d2009-06-12 18:26:56 +00001006 Info.FirstArg = Param;
1007 Info.SecondArg = Arg;
1008 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Douglas Gregor199d9912009-06-05 00:53:49 +00001011 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001012 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001013 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001014 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001015 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Douglas Gregorf67875d2009-06-12 18:26:56 +00001018 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001019}
1020
Douglas Gregor20a55e22010-12-22 18:17:10 +00001021/// \brief Determine whether there is a template argument to be used for
1022/// deduction.
1023///
1024/// This routine "expands" argument packs in-place, overriding its input
1025/// parameters so that \c Args[ArgIdx] will be the available template argument.
1026///
1027/// \returns true if there is another template argument (which will be at
1028/// \c Args[ArgIdx]), false otherwise.
1029static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1030 unsigned &ArgIdx,
1031 unsigned &NumArgs) {
1032 if (ArgIdx == NumArgs)
1033 return false;
1034
1035 const TemplateArgument &Arg = Args[ArgIdx];
1036 if (Arg.getKind() != TemplateArgument::Pack)
1037 return true;
1038
1039 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1040 Args = Arg.pack_begin();
1041 NumArgs = Arg.pack_size();
1042 ArgIdx = 0;
1043 return ArgIdx < NumArgs;
1044}
1045
Douglas Gregore02e2622010-12-22 21:19:48 +00001046/// \brief Retrieve the depth and index of an unexpanded parameter pack.
1047static std::pair<unsigned, unsigned>
1048getDepthAndIndex(UnexpandedParameterPack UPP) {
1049 if (const TemplateTypeParmType *TTP
1050 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
1051 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1052
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001053 NamedDecl *ND = UPP.first.get<NamedDecl *>();
1054 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001055 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1056
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001057 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001058 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
1059
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001060 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
Douglas Gregore02e2622010-12-22 21:19:48 +00001061 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1062}
1063
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001064/// \brief Helper function to build a TemplateParameter when we don't
1065/// know its type statically.
1066static TemplateParameter makeTemplateParameter(Decl *D) {
1067 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1068 return TemplateParameter(TTP);
1069 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1070 return TemplateParameter(NTTP);
1071
1072 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1073}
1074
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001075/// \brief Determine whether the given set of template arguments has a pack
1076/// expansion that is not the last template argument.
1077static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1078 unsigned NumArgs) {
1079 unsigned ArgIdx = 0;
1080 while (ArgIdx < NumArgs) {
1081 const TemplateArgument &Arg = Args[ArgIdx];
1082
1083 // Unwrap argument packs.
1084 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1085 Args = Arg.pack_begin();
1086 NumArgs = Arg.pack_size();
1087 ArgIdx = 0;
1088 continue;
1089 }
1090
1091 ++ArgIdx;
1092 if (ArgIdx == NumArgs)
1093 return false;
1094
1095 if (Arg.isPackExpansion())
1096 return true;
1097 }
1098
1099 return false;
1100}
1101
Douglas Gregor20a55e22010-12-22 18:17:10 +00001102static Sema::TemplateDeductionResult
1103DeduceTemplateArguments(Sema &S,
1104 TemplateParameterList *TemplateParams,
1105 const TemplateArgument *Params, unsigned NumParams,
1106 const TemplateArgument *Args, unsigned NumArgs,
1107 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001108 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1109 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001110 // C++0x [temp.deduct.type]p9:
1111 // If the template argument list of P contains a pack expansion that is not
1112 // the last template argument, the entire template argument list is a
1113 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001114 if (hasPackExpansionBeforeEnd(Params, NumParams))
1115 return Sema::TDK_Success;
1116
Douglas Gregore02e2622010-12-22 21:19:48 +00001117 // C++0x [temp.deduct.type]p9:
1118 // If P has a form that contains <T> or <i>, then each argument Pi of the
1119 // respective template argument list P is compared with the corresponding
1120 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001121 unsigned ArgIdx = 0, ParamIdx = 0;
1122 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1123 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001124 // FIXME: Variadic templates.
1125 // What do we do if the argument is a pack expansion?
1126
Douglas Gregor20a55e22010-12-22 18:17:10 +00001127 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001128 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001129
1130 // Check whether we have enough arguments.
1131 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001132 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1133 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001134
Douglas Gregore02e2622010-12-22 21:19:48 +00001135 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001136 if (Sema::TemplateDeductionResult Result
1137 = DeduceTemplateArguments(S, TemplateParams,
1138 Params[ParamIdx], Args[ArgIdx],
1139 Info, Deduced))
1140 return Result;
1141
1142 // Move to the next argument.
1143 ++ArgIdx;
1144 continue;
1145 }
1146
Douglas Gregore02e2622010-12-22 21:19:48 +00001147 // The parameter is a pack expansion.
1148
1149 // C++0x [temp.deduct.type]p9:
1150 // If Pi is a pack expansion, then the pattern of Pi is compared with
1151 // each remaining argument in the template argument list of A. Each
1152 // comparison deduces template arguments for subsequent positions in the
1153 // template parameter packs expanded by Pi.
1154 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1155
1156 // Compute the set of template parameter indices that correspond to
1157 // parameter packs expanded by the pack expansion.
1158 llvm::SmallVector<unsigned, 2> PackIndices;
1159 {
1160 llvm::BitVector SawIndices(TemplateParams->size());
1161 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1162 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1163 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1164 unsigned Depth, Index;
1165 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1166 if (Depth == 0 && !SawIndices[Index]) {
1167 SawIndices[Index] = true;
1168 PackIndices.push_back(Index);
1169 }
1170 }
1171 }
1172 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1173
1174 // FIXME: If there are no remaining arguments, we can bail out early
1175 // and set any deduced parameter packs to an empty argument pack.
1176 // The latter part of this is a (minor) correctness issue.
1177
1178 // Save the deduced template arguments for each parameter pack expanded
1179 // by this pack expansion, then clear out the deduction.
1180 llvm::SmallVector<DeducedTemplateArgument, 2>
1181 SavedPacks(PackIndices.size());
1182 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1183 SavedPacks[I] = Deduced[PackIndices[I]];
1184 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1185 }
1186
1187 // Keep track of the deduced template arguments for each parameter pack
1188 // expanded by this pack expansion (the outer index) and for each
1189 // template argument (the inner SmallVectors).
1190 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1191 NewlyDeducedPacks(PackIndices.size());
1192 bool HasAnyArguments = false;
1193 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1194 HasAnyArguments = true;
1195
1196 // Deduce template arguments from the pattern.
1197 if (Sema::TemplateDeductionResult Result
1198 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1199 Info, Deduced))
1200 return Result;
1201
1202 // Capture the deduced template arguments for each parameter pack expanded
1203 // by this pack expansion, add them to the list of arguments we've deduced
1204 // for that pack, then clear out the deduced argument.
1205 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1206 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1207 if (!DeducedArg.isNull()) {
1208 NewlyDeducedPacks[I].push_back(DeducedArg);
1209 DeducedArg = DeducedTemplateArgument();
1210 }
1211 }
1212
1213 ++ArgIdx;
1214 }
1215
1216 // Build argument packs for each of the parameter packs expanded by this
1217 // pack expansion.
1218 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1219 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1220 // We were not able to deduce anything for this parameter pack,
1221 // so just restore the saved argument pack.
1222 Deduced[PackIndices[I]] = SavedPacks[I];
1223 continue;
1224 }
1225
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001226 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001227
1228 if (NewlyDeducedPacks[I].empty()) {
1229 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001230 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1231 } else {
1232 TemplateArgument *ArgumentPack
1233 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1234 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1235 ArgumentPack);
1236 NewPack
1237 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001238 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001239 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1240 }
1241
1242 DeducedTemplateArgument Result
1243 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1244 if (Result.isNull()) {
1245 Info.Param
1246 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1247 Info.FirstArg = SavedPacks[I];
1248 Info.SecondArg = NewPack;
1249 return Sema::TDK_Inconsistent;
1250 }
1251
1252 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001253 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001254 }
1255
1256 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001257 if (NumberOfArgumentsMustMatch &&
1258 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001259 return Sema::TDK_TooManyArguments;
1260
1261 return Sema::TDK_Success;
1262}
1263
Mike Stump1eb44332009-09-09 15:08:12 +00001264static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001265DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001266 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001267 const TemplateArgumentList &ParamList,
1268 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001269 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001270 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001271 return DeduceTemplateArguments(S, TemplateParams,
1272 ParamList.data(), ParamList.size(),
1273 ArgList.data(), ArgList.size(),
1274 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001275}
1276
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001277/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001278static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001279 const TemplateArgument &X,
1280 const TemplateArgument &Y) {
1281 if (X.getKind() != Y.getKind())
1282 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001284 switch (X.getKind()) {
1285 case TemplateArgument::Null:
1286 assert(false && "Comparing NULL template argument");
1287 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001289 case TemplateArgument::Type:
1290 return Context.getCanonicalType(X.getAsType()) ==
1291 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001293 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001294 return X.getAsDecl()->getCanonicalDecl() ==
1295 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Douglas Gregor788cd062009-11-11 01:00:40 +00001297 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001298 case TemplateArgument::TemplateExpansion:
1299 return Context.getCanonicalTemplateName(
1300 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1301 Context.getCanonicalTemplateName(
1302 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001303
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001304 case TemplateArgument::Integral:
1305 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Douglas Gregor788cd062009-11-11 01:00:40 +00001307 case TemplateArgument::Expression: {
1308 llvm::FoldingSetNodeID XID, YID;
1309 X.getAsExpr()->Profile(XID, Context, true);
1310 Y.getAsExpr()->Profile(YID, Context, true);
1311 return XID == YID;
1312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001314 case TemplateArgument::Pack:
1315 if (X.pack_size() != Y.pack_size())
1316 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001317
1318 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1319 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001320 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001321 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001322 if (!isSameTemplateArg(Context, *XP, *YP))
1323 return false;
1324
1325 return true;
1326 }
1327
1328 return false;
1329}
1330
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001331/// \brief Allocate a TemplateArgumentLoc where all locations have
1332/// been initialized to the given location.
1333///
1334/// \param S The semantic analysis object.
1335///
1336/// \param The template argument we are producing template argument
1337/// location information for.
1338///
1339/// \param NTTPType For a declaration template argument, the type of
1340/// the non-type template parameter that corresponds to this template
1341/// argument.
1342///
1343/// \param Loc The source location to use for the resulting template
1344/// argument.
1345static TemplateArgumentLoc
1346getTrivialTemplateArgumentLoc(Sema &S,
1347 const TemplateArgument &Arg,
1348 QualType NTTPType,
1349 SourceLocation Loc) {
1350 switch (Arg.getKind()) {
1351 case TemplateArgument::Null:
1352 llvm_unreachable("Can't get a NULL template argument here");
1353 break;
1354
1355 case TemplateArgument::Type:
1356 return TemplateArgumentLoc(Arg,
1357 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1358
1359 case TemplateArgument::Declaration: {
1360 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001361 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001362 .takeAs<Expr>();
1363 return TemplateArgumentLoc(TemplateArgument(E), E);
1364 }
1365
1366 case TemplateArgument::Integral: {
1367 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001368 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001369 return TemplateArgumentLoc(TemplateArgument(E), E);
1370 }
1371
1372 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001373 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1374
1375 case TemplateArgument::TemplateExpansion:
1376 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1377
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001378 case TemplateArgument::Expression:
1379 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1380
1381 case TemplateArgument::Pack:
1382 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1383 }
1384
1385 return TemplateArgumentLoc();
1386}
1387
1388
1389/// \brief Convert the given deduced template argument and add it to the set of
1390/// fully-converted template arguments.
1391static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1392 DeducedTemplateArgument Arg,
1393 NamedDecl *Template,
1394 QualType NTTPType,
1395 TemplateDeductionInfo &Info,
1396 bool InFunctionTemplate,
1397 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1398 if (Arg.getKind() == TemplateArgument::Pack) {
1399 // This is a template argument pack, so check each of its arguments against
1400 // the template parameter.
1401 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1402 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
1403 PAEnd = Arg.pack_end();
1404 PA != PAEnd; ++PA) {
1405 DeducedTemplateArgument InnerArg(*PA);
1406 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1407 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1408 NTTPType, Info,
1409 InFunctionTemplate, PackedArgsBuilder))
1410 return true;
1411 }
1412
1413 // Create the resulting argument pack.
1414 TemplateArgument *PackedArgs = 0;
1415 if (!PackedArgsBuilder.empty()) {
1416 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1417 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1418 }
1419 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1420 return false;
1421 }
1422
1423 // Convert the deduced template argument into a template
1424 // argument that we can check, almost as if the user had written
1425 // the template argument explicitly.
1426 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1427 Info.getLocation());
1428
1429 // Check the template argument, converting it as necessary.
1430 return S.CheckTemplateArgument(Param, ArgLoc,
1431 Template,
1432 Template->getLocation(),
1433 Template->getSourceRange().getEnd(),
1434 Output,
1435 InFunctionTemplate
1436 ? (Arg.wasDeducedFromArrayBound()
1437 ? Sema::CTAK_DeducedFromArrayBound
1438 : Sema::CTAK_Deduced)
1439 : Sema::CTAK_Specified);
1440}
1441
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001442/// Complete template argument deduction for a class template partial
1443/// specialization.
1444static Sema::TemplateDeductionResult
1445FinishTemplateArgumentDeduction(Sema &S,
1446 ClassTemplatePartialSpecializationDecl *Partial,
1447 const TemplateArgumentList &TemplateArgs,
1448 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001449 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001450 // Trap errors.
1451 Sema::SFINAETrap Trap(S);
1452
1453 Sema::ContextRAII SavedContext(S, Partial);
1454
1455 // C++ [temp.deduct.type]p2:
1456 // [...] or if any template argument remains neither deduced nor
1457 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001458 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001459 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1460 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001461 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001462 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001463 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001464 return Sema::TDK_Incomplete;
1465 }
1466
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001467 // We have deduced this argument, so it still needs to be
1468 // checked and converted.
1469
1470 // First, for a non-type template parameter type that is
1471 // initialized by a declaration, we need the type of the
1472 // corresponding non-type template parameter.
1473 QualType NTTPType;
1474 if (NonTypeTemplateParmDecl *NTTP
1475 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1476 NTTPType = NTTP->getType();
1477
1478 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1479 Partial, NTTPType, Info, false,
1480 Builder)) {
1481 Info.Param = makeTemplateParameter(Param);
1482 // FIXME: These template arguments are temporary. Free them!
1483 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1484 Builder.size()));
1485 return Sema::TDK_SubstitutionFailure;
1486 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001487 }
1488
1489 // Form the template argument list from the deduced template arguments.
1490 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001491 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1492 Builder.size());
1493
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001494 Info.reset(DeducedArgumentList);
1495
1496 // Substitute the deduced template arguments into the template
1497 // arguments of the class template partial specialization, and
1498 // verify that the instantiated template arguments are both valid
1499 // and are equivalent to the template arguments originally provided
1500 // to the class template.
1501 // FIXME: Do we have to correct the types of deduced non-type template
1502 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001503 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001504 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1505 const TemplateArgumentLoc *PartialTemplateArgs
1506 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001507
1508 // Note that we don't provide the langle and rangle locations.
1509 TemplateArgumentListInfo InstArgs;
1510
Douglas Gregore02e2622010-12-22 21:19:48 +00001511 if (S.Subst(PartialTemplateArgs,
1512 Partial->getNumTemplateArgsAsWritten(),
1513 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1514 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1515 if (ParamIdx >= Partial->getTemplateParameters()->size())
1516 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1517
1518 Decl *Param
1519 = const_cast<NamedDecl *>(
1520 Partial->getTemplateParameters()->getParam(ParamIdx));
1521 Info.Param = makeTemplateParameter(Param);
1522 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1523 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001524 }
1525
Douglas Gregor910f8002010-11-07 23:05:16 +00001526 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001527 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001528 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001529 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001530
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001531 TemplateParameterList *TemplateParams
1532 = ClassTemplate->getTemplateParameters();
1533 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001534 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001535 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001536 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001537 Info.FirstArg = TemplateArgs[I];
1538 Info.SecondArg = InstArg;
1539 return Sema::TDK_NonDeducedMismatch;
1540 }
1541 }
1542
1543 if (Trap.hasErrorOccurred())
1544 return Sema::TDK_SubstitutionFailure;
1545
1546 return Sema::TDK_Success;
1547}
1548
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001549/// \brief Perform template argument deduction to determine whether
1550/// the given template arguments match the given class template
1551/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001552Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001553Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001554 const TemplateArgumentList &TemplateArgs,
1555 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001556 // C++ [temp.class.spec.match]p2:
1557 // A partial specialization matches a given actual template
1558 // argument list if the template arguments of the partial
1559 // specialization can be deduced from the actual template argument
1560 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001561 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001562 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001563 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001564 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001565 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001566 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001567 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001568 TemplateArgs, Info, Deduced))
1569 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001570
Douglas Gregor637a4092009-06-10 23:47:09 +00001571 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001572 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001573 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001574 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001575
Douglas Gregorbb260412009-06-14 08:02:22 +00001576 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001577 return Sema::TDK_SubstitutionFailure;
1578
1579 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1580 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001581}
Douglas Gregor031a5882009-06-13 00:26:55 +00001582
Douglas Gregor41128772009-06-26 23:27:24 +00001583/// \brief Determine whether the given type T is a simple-template-id type.
1584static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001585 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001586 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001587 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Douglas Gregor41128772009-06-26 23:27:24 +00001589 return false;
1590}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001591
1592/// \brief Substitute the explicitly-provided template arguments into the
1593/// given function template according to C++ [temp.arg.explicit].
1594///
1595/// \param FunctionTemplate the function template into which the explicit
1596/// template arguments will be substituted.
1597///
Mike Stump1eb44332009-09-09 15:08:12 +00001598/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001599/// arguments.
1600///
Mike Stump1eb44332009-09-09 15:08:12 +00001601/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001602/// with the converted and checked explicit template arguments.
1603///
Mike Stump1eb44332009-09-09 15:08:12 +00001604/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001605/// parameters.
1606///
1607/// \param FunctionType if non-NULL, the result type of the function template
1608/// will also be instantiated and the pointed-to value will be updated with
1609/// the instantiated function type.
1610///
1611/// \param Info if substitution fails for any reason, this object will be
1612/// populated with more information about the failure.
1613///
1614/// \returns TDK_Success if substitution was successful, or some failure
1615/// condition.
1616Sema::TemplateDeductionResult
1617Sema::SubstituteExplicitTemplateArguments(
1618 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001619 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001620 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001621 llvm::SmallVectorImpl<QualType> &ParamTypes,
1622 QualType *FunctionType,
1623 TemplateDeductionInfo &Info) {
1624 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1625 TemplateParameterList *TemplateParams
1626 = FunctionTemplate->getTemplateParameters();
1627
John McCalld5532b62009-11-23 01:53:49 +00001628 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001629 // No arguments to substitute; just copy over the parameter types and
1630 // fill in the function type.
1631 for (FunctionDecl::param_iterator P = Function->param_begin(),
1632 PEnd = Function->param_end();
1633 P != PEnd;
1634 ++P)
1635 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor83314aa2009-07-08 20:55:45 +00001637 if (FunctionType)
1638 *FunctionType = Function->getType();
1639 return TDK_Success;
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregor83314aa2009-07-08 20:55:45 +00001642 // Substitution of the explicit template arguments into a function template
1643 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001644 SFINAETrap Trap(*this);
1645
Douglas Gregor83314aa2009-07-08 20:55:45 +00001646 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001647 // Template arguments that are present shall be specified in the
1648 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001649 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001650 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001651 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001652
1653 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001654 // explicitly-specified template arguments against this function template,
1655 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001656 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001657 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001658 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1659 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001660 if (Inst)
1661 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregor83314aa2009-07-08 20:55:45 +00001663 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001664 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001665 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001666 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001667 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001668 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001669 if (Index >= TemplateParams->size())
1670 Index = TemplateParams->size() - 1;
1671 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001672 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregor83314aa2009-07-08 20:55:45 +00001675 // Form the template argument list from the explicitly-specified
1676 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001677 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001678 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001679 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001680
John McCalldf41f182010-10-12 19:40:14 +00001681 // Template argument deduction and the final substitution should be
1682 // done in the context of the templated declaration. Explicit
1683 // argument substitution, on the other hand, needs to happen in the
1684 // calling context.
1685 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1686
Douglas Gregor83314aa2009-07-08 20:55:45 +00001687 // Instantiate the types of each of the function parameters given the
1688 // explicitly-specified template arguments.
1689 for (FunctionDecl::param_iterator P = Function->param_begin(),
1690 PEnd = Function->param_end();
1691 P != PEnd;
1692 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001693 QualType ParamType
1694 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001695 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1696 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001697 if (ParamType.isNull() || Trap.hasErrorOccurred())
1698 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Douglas Gregor83314aa2009-07-08 20:55:45 +00001700 ParamTypes.push_back(ParamType);
1701 }
1702
1703 // If the caller wants a full function type back, instantiate the return
1704 // type and form that function type.
1705 if (FunctionType) {
1706 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001707 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001708 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001709 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001710
1711 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001712 = SubstType(Proto->getResultType(),
1713 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1714 Function->getTypeSpecStartLoc(),
1715 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001716 if (ResultType.isNull() || Trap.hasErrorOccurred())
1717 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001718
1719 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001720 ParamTypes.data(), ParamTypes.size(),
1721 Proto->isVariadic(),
1722 Proto->getTypeQuals(),
1723 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001724 Function->getDeclName(),
1725 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001726 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1727 return TDK_SubstitutionFailure;
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Douglas Gregor83314aa2009-07-08 20:55:45 +00001730 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001731 // Trailing template arguments that can be deduced (14.8.2) may be
1732 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001733 // template arguments can be deduced, they may all be omitted; in this
1734 // case, the empty template argument list <> itself may also be omitted.
1735 //
1736 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001737 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001738 Deduced.reserve(TemplateParams->size());
1739 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001740 Deduced.push_back(ExplicitArgumentList->get(I));
1741
Douglas Gregor83314aa2009-07-08 20:55:45 +00001742 return TDK_Success;
1743}
1744
Mike Stump1eb44332009-09-09 15:08:12 +00001745/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001746/// checking the deduced template arguments for completeness and forming
1747/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001748Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001749Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001750 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1751 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001752 FunctionDecl *&Specialization,
1753 TemplateDeductionInfo &Info) {
1754 TemplateParameterList *TemplateParams
1755 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor83314aa2009-07-08 20:55:45 +00001757 // Template argument deduction for function templates in a SFINAE context.
1758 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001759 SFINAETrap Trap(*this);
1760
Douglas Gregor83314aa2009-07-08 20:55:45 +00001761 // Enter a new template instantiation context while we instantiate the
1762 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001763 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001764 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001765 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1766 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001767 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001768 return TDK_InstantiationDepth;
1769
John McCall96db3102010-04-29 01:18:58 +00001770 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001771
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001772 // C++ [temp.deduct.type]p2:
1773 // [...] or if any template argument remains neither deduced nor
1774 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001775 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001776 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1777 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001778
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001779 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001780 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001781 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001782 // argument, because it was explicitly-specified. Just record the
1783 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001784 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001785 continue;
1786 }
1787
1788 // We have deduced this argument, so it still needs to be
1789 // checked and converted.
1790
1791 // First, for a non-type template parameter type that is
1792 // initialized by a declaration, we need the type of the
1793 // corresponding non-type template parameter.
1794 QualType NTTPType;
1795 if (NonTypeTemplateParmDecl *NTTP
1796 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001797 NTTPType = NTTP->getType();
1798 if (NTTPType->isDependentType()) {
1799 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1800 Builder.data(), Builder.size());
1801 NTTPType = SubstType(NTTPType,
1802 MultiLevelTemplateArgumentList(TemplateArgs),
1803 NTTP->getLocation(),
1804 NTTP->getDeclName());
1805 if (NTTPType.isNull()) {
1806 Info.Param = makeTemplateParameter(Param);
1807 // FIXME: These template arguments are temporary. Free them!
1808 Info.reset(TemplateArgumentList::CreateCopy(Context,
1809 Builder.data(),
1810 Builder.size()));
1811 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00001812 }
1813 }
1814 }
1815
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001816 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
1817 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001818 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001819 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001820 // FIXME: These template arguments are temporary. Free them!
1821 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001822 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001823 return TDK_SubstitutionFailure;
1824 }
1825
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001826 continue;
1827 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001828
1829 // C++0x [temp.arg.explicit]p3:
1830 // A trailing template parameter pack (14.5.3) not otherwise deduced will
1831 // be deduced to an empty sequence of template arguments.
1832 // FIXME: Where did the word "trailing" come from?
1833 if (Param->isTemplateParameterPack()) {
1834 Builder.push_back(TemplateArgument(0, 0));
1835 continue;
1836 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001837
1838 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001839 TemplateArgumentLoc DefArg
1840 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1841 FunctionTemplate->getLocation(),
1842 FunctionTemplate->getSourceRange().getEnd(),
1843 Param,
1844 Builder);
1845
1846 // If there was no default argument, deduction is incomplete.
1847 if (DefArg.getArgument().isNull()) {
1848 Info.Param = makeTemplateParameter(
1849 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1850 return TDK_Incomplete;
1851 }
1852
1853 // Check whether we can actually use the default argument.
1854 if (CheckTemplateArgument(Param, DefArg,
1855 FunctionTemplate,
1856 FunctionTemplate->getLocation(),
1857 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001858 Builder,
1859 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001860 Info.Param = makeTemplateParameter(
1861 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001862 // FIXME: These template arguments are temporary. Free them!
1863 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1864 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001865 return TDK_SubstitutionFailure;
1866 }
1867
1868 // If we get here, we successfully used the default template argument.
1869 }
1870
1871 // Form the template argument list from the deduced template arguments.
1872 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001873 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001874 Info.reset(DeducedArgumentList);
1875
Mike Stump1eb44332009-09-09 15:08:12 +00001876 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001877 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001878 DeclContext *Owner = FunctionTemplate->getDeclContext();
1879 if (FunctionTemplate->getFriendObjectKind())
1880 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001881 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001882 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001883 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001884 if (!Specialization)
1885 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Douglas Gregorf8825742009-09-15 18:26:13 +00001887 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1888 FunctionTemplate->getCanonicalDecl());
1889
Mike Stump1eb44332009-09-09 15:08:12 +00001890 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001891 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001892 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1893 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001894 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Douglas Gregor83314aa2009-07-08 20:55:45 +00001896 // There may have been an error that did not prevent us from constructing a
1897 // declaration. Mark the declaration invalid and return with a substitution
1898 // failure.
1899 if (Trap.hasErrorOccurred()) {
1900 Specialization->setInvalidDecl(true);
1901 return TDK_SubstitutionFailure;
1902 }
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregor9b623632010-10-12 23:32:35 +00001904 // If we suppressed any diagnostics while performing template argument
1905 // deduction, and if we haven't already instantiated this declaration,
1906 // keep track of these diagnostics. They'll be emitted if this specialization
1907 // is actually used.
1908 if (Info.diag_begin() != Info.diag_end()) {
1909 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1910 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1911 if (Pos == SuppressedDiagnostics.end())
1912 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1913 .append(Info.diag_begin(), Info.diag_end());
1914 }
1915
Mike Stump1eb44332009-09-09 15:08:12 +00001916 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001917}
1918
John McCall9c72c602010-08-27 09:08:28 +00001919/// Gets the type of a function for template-argument-deducton
1920/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001921static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001922 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001923 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001924 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001925 if (Method->isInstance()) {
1926 // An instance method that's referenced in a form that doesn't
1927 // look like a member pointer is just invalid.
1928 if (!R.HasFormOfMemberPointer) return QualType();
1929
John McCalleff92132010-02-02 02:21:27 +00001930 return Context.getMemberPointerType(Fn->getType(),
1931 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001932 }
1933
1934 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001935 return Context.getPointerType(Fn->getType());
1936}
1937
1938/// Apply the deduction rules for overload sets.
1939///
1940/// \return the null type if this argument should be treated as an
1941/// undeduced context
1942static QualType
1943ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001944 Expr *Arg, QualType ParamType,
1945 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001946
1947 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001948
John McCall9c72c602010-08-27 09:08:28 +00001949 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001950
Douglas Gregor75f21af2010-08-30 21:04:23 +00001951 // C++0x [temp.deduct.call]p4
1952 unsigned TDF = 0;
1953 if (ParamWasReference)
1954 TDF |= TDF_ParamWithReferenceType;
1955 if (R.IsAddressOfOperand)
1956 TDF |= TDF_IgnoreQualifiers;
1957
John McCalleff92132010-02-02 02:21:27 +00001958 // If there were explicit template arguments, we can only find
1959 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1960 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001961 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001962 // But we can still look for an explicit specialization.
1963 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001964 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001965 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001966 return QualType();
1967 }
1968
1969 // C++0x [temp.deduct.call]p6:
1970 // When P is a function type, pointer to function type, or pointer
1971 // to member function type:
1972
1973 if (!ParamType->isFunctionType() &&
1974 !ParamType->isFunctionPointerType() &&
1975 !ParamType->isMemberFunctionPointerType())
1976 return QualType();
1977
1978 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001979 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1980 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001981 NamedDecl *D = (*I)->getUnderlyingDecl();
1982
1983 // - If the argument is an overload set containing one or more
1984 // function templates, the parameter is treated as a
1985 // non-deduced context.
1986 if (isa<FunctionTemplateDecl>(D))
1987 return QualType();
1988
1989 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001990 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1991 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001992
Douglas Gregor75f21af2010-08-30 21:04:23 +00001993 // Function-to-pointer conversion.
1994 if (!ParamWasReference && ParamType->isPointerType() &&
1995 ArgType->isFunctionType())
1996 ArgType = S.Context.getPointerType(ArgType);
1997
John McCalleff92132010-02-02 02:21:27 +00001998 // - If the argument is an overload set (not containing function
1999 // templates), trial argument deduction is attempted using each
2000 // of the members of the set. If deduction succeeds for only one
2001 // of the overload set members, that member is used as the
2002 // argument value for the deduction. If deduction succeeds for
2003 // more than one member of the overload set the parameter is
2004 // treated as a non-deduced context.
2005
2006 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2007 // Type deduction is done independently for each P/A pair, and
2008 // the deduced template argument values are then combined.
2009 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002010 llvm::SmallVector<DeducedTemplateArgument, 8>
2011 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002012 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002013 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002014 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002015 ParamType, ArgType,
2016 Info, Deduced, TDF);
2017 if (Result) continue;
2018 if (!Match.isNull()) return QualType();
2019 Match = ArgType;
2020 }
2021
2022 return Match;
2023}
2024
Douglas Gregore53060f2009-06-25 22:08:12 +00002025/// \brief Perform template argument deduction from a function call
2026/// (C++ [temp.deduct.call]).
2027///
2028/// \param FunctionTemplate the function template for which we are performing
2029/// template argument deduction.
2030///
Douglas Gregor48026d22010-01-11 18:40:55 +00002031/// \param ExplicitTemplateArguments the explicit template arguments provided
2032/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002033///
Douglas Gregore53060f2009-06-25 22:08:12 +00002034/// \param Args the function call arguments
2035///
2036/// \param NumArgs the number of arguments in Args
2037///
Douglas Gregor48026d22010-01-11 18:40:55 +00002038/// \param Name the name of the function being called. This is only significant
2039/// when the function template is a conversion function template, in which
2040/// case this routine will also perform template argument deduction based on
2041/// the function to which
2042///
Douglas Gregore53060f2009-06-25 22:08:12 +00002043/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002044/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002045/// template argument deduction.
2046///
2047/// \param Info the argument will be updated to provide additional information
2048/// about template argument deduction.
2049///
2050/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002051Sema::TemplateDeductionResult
2052Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002053 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002054 Expr **Args, unsigned NumArgs,
2055 FunctionDecl *&Specialization,
2056 TemplateDeductionInfo &Info) {
2057 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002058
Douglas Gregore53060f2009-06-25 22:08:12 +00002059 // C++ [temp.deduct.call]p1:
2060 // Template argument deduction is done by comparing each function template
2061 // parameter type (call it P) with the type of the corresponding argument
2062 // of the call (call it A) as described below.
2063 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002064 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002065 return TDK_TooFewArguments;
2066 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002067 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002068 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00002069 if (!Proto->isVariadic())
2070 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Douglas Gregore53060f2009-06-25 22:08:12 +00002072 CheckArgs = Function->getNumParams();
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002075 // The types of the parameters from which we will perform template argument
2076 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002077 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002078 TemplateParameterList *TemplateParams
2079 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002080 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002081 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002082 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002083 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002084 TemplateDeductionResult Result =
2085 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002086 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002087 Deduced,
2088 ParamTypes,
2089 0,
2090 Info);
2091 if (Result)
2092 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002093
2094 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002095 } else {
2096 // Just fill in the parameter types from the function declaration.
2097 for (unsigned I = 0; I != CheckArgs; ++I)
2098 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002101 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002102 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002103 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002104 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002105 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor75f21af2010-08-30 21:04:23 +00002107 // C++0x [temp.deduct.call]p3:
2108 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2109 // are ignored for type deduction.
2110 if (ParamType.getCVRQualifiers())
2111 ParamType = ParamType.getLocalUnqualifiedType();
2112 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2113 if (ParamRefType) {
2114 // [...] If P is a reference type, the type referred to by P is used
2115 // for type deduction.
2116 ParamType = ParamRefType->getPointeeType();
2117 }
2118
John McCalleff92132010-02-02 02:21:27 +00002119 // Overload sets usually make this parameter an undeduced
2120 // context, but there are sometimes special circumstances.
2121 if (ArgType == Context.OverloadTy) {
2122 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002123 Args[I], ParamType,
2124 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002125 if (ArgType.isNull())
2126 continue;
2127 }
2128
Douglas Gregor75f21af2010-08-30 21:04:23 +00002129 if (ParamRefType) {
2130 // C++0x [temp.deduct.call]p3:
2131 // [...] If P is of the form T&&, where T is a template parameter, and
2132 // the argument is an lvalue, the type A& is used in place of A for
2133 // type deduction.
2134 if (ParamRefType->isRValueReferenceType() &&
2135 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002136 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002137 ArgType = Context.getLValueReferenceType(ArgType);
2138 } else {
2139 // C++ [temp.deduct.call]p2:
2140 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002141 // - If A is an array type, the pointer type produced by the
2142 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002143 // A for type deduction; otherwise,
2144 if (ArgType->isArrayType())
2145 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002146 // - If A is a function type, the pointer type produced by the
2147 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002148 // of A for type deduction; otherwise,
2149 else if (ArgType->isFunctionType())
2150 ArgType = Context.getPointerType(ArgType);
2151 else {
2152 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2153 // type are ignored for type deduction.
2154 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002155 if (ArgType.getCVRQualifiers())
2156 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002157 }
2158 }
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Douglas Gregore53060f2009-06-25 22:08:12 +00002160 // C++0x [temp.deduct.call]p4:
2161 // In general, the deduction process attempts to find template argument
2162 // values that will make the deduced A identical to A (after the type A
2163 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002164 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Douglas Gregor508f1c82009-06-26 23:10:12 +00002166 // - If the original P is a reference type, the deduced A (i.e., the
2167 // type referred to by the reference) can be more cv-qualified than
2168 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002169 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002170 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002171 // - The transformed A can be another pointer or pointer to member
2172 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002173 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002174 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2175 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002176 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002177 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002178 // transformed A can be a derived class of the deduced A. Likewise,
2179 // if P is a pointer to a class of the form simple-template-id, the
2180 // transformed A can be a pointer to a derived class pointed to by
2181 // the deduced A.
2182 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002183 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002184 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002185 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002186 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Douglas Gregore53060f2009-06-25 22:08:12 +00002188 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002189 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002190 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002191 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002192 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002194 // FIXME: we need to check that the deduced A is the same as A,
2195 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002196 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002197
Mike Stump1eb44332009-09-09 15:08:12 +00002198 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002199 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002200 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002201}
2202
Douglas Gregor83314aa2009-07-08 20:55:45 +00002203/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002204/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2205/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002206///
2207/// \param FunctionTemplate the function template for which we are performing
2208/// template argument deduction.
2209///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002210/// \param ExplicitTemplateArguments the explicitly-specified template
2211/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002212///
2213/// \param ArgFunctionType the function type that will be used as the
2214/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002215/// function template's function type. This type may be NULL, if there is no
2216/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002217///
2218/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002219/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002220/// template argument deduction.
2221///
2222/// \param Info the argument will be updated to provide additional information
2223/// about template argument deduction.
2224///
2225/// \returns the result of template argument deduction.
2226Sema::TemplateDeductionResult
2227Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002228 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002229 QualType ArgFunctionType,
2230 FunctionDecl *&Specialization,
2231 TemplateDeductionInfo &Info) {
2232 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2233 TemplateParameterList *TemplateParams
2234 = FunctionTemplate->getTemplateParameters();
2235 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Douglas Gregor83314aa2009-07-08 20:55:45 +00002237 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002238 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002239 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2240 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002241 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002242 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002243 if (TemplateDeductionResult Result
2244 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002245 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002246 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002247 &FunctionType, Info))
2248 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002249
2250 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002251 }
2252
2253 // Template argument deduction for function templates in a SFINAE context.
2254 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002255 SFINAETrap Trap(*this);
2256
John McCalleff92132010-02-02 02:21:27 +00002257 Deduced.resize(TemplateParams->size());
2258
Douglas Gregor4b52e252009-12-21 23:17:24 +00002259 if (!ArgFunctionType.isNull()) {
2260 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002261 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002262 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002263 FunctionType, ArgFunctionType, Info,
2264 Deduced, 0))
2265 return Result;
2266 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002267
2268 if (TemplateDeductionResult Result
2269 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2270 NumExplicitlySpecified,
2271 Specialization, Info))
2272 return Result;
2273
2274 // If the requested function type does not match the actual type of the
2275 // specialization, template argument deduction fails.
2276 if (!ArgFunctionType.isNull() &&
2277 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2278 return TDK_NonDeducedMismatch;
2279
2280 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002281}
2282
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002283/// \brief Deduce template arguments for a templated conversion
2284/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2285/// conversion function template specialization.
2286Sema::TemplateDeductionResult
2287Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2288 QualType ToType,
2289 CXXConversionDecl *&Specialization,
2290 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002291 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002292 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2293 QualType FromType = Conv->getConversionType();
2294
2295 // Canonicalize the types for deduction.
2296 QualType P = Context.getCanonicalType(FromType);
2297 QualType A = Context.getCanonicalType(ToType);
2298
2299 // C++0x [temp.deduct.conv]p3:
2300 // If P is a reference type, the type referred to by P is used for
2301 // type deduction.
2302 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2303 P = PRef->getPointeeType();
2304
2305 // C++0x [temp.deduct.conv]p3:
2306 // If A is a reference type, the type referred to by A is used
2307 // for type deduction.
2308 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2309 A = ARef->getPointeeType();
2310 // C++ [temp.deduct.conv]p2:
2311 //
Mike Stump1eb44332009-09-09 15:08:12 +00002312 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002313 else {
2314 assert(!A->isReferenceType() && "Reference types were handled above");
2315
2316 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002317 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002318 // of P for type deduction; otherwise,
2319 if (P->isArrayType())
2320 P = Context.getArrayDecayedType(P);
2321 // - If P is a function type, the pointer type produced by the
2322 // function-to-pointer standard conversion (4.3) is used in
2323 // place of P for type deduction; otherwise,
2324 else if (P->isFunctionType())
2325 P = Context.getPointerType(P);
2326 // - If P is a cv-qualified type, the top level cv-qualifiers of
2327 // P’s type are ignored for type deduction.
2328 else
2329 P = P.getUnqualifiedType();
2330
2331 // C++0x [temp.deduct.conv]p3:
2332 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2333 // type are ignored for type deduction.
2334 A = A.getUnqualifiedType();
2335 }
2336
2337 // Template argument deduction for function templates in a SFINAE context.
2338 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002339 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002340
2341 // C++ [temp.deduct.conv]p1:
2342 // Template argument deduction is done by comparing the return
2343 // type of the template conversion function (call it P) with the
2344 // type that is required as the result of the conversion (call it
2345 // A) as described in 14.8.2.4.
2346 TemplateParameterList *TemplateParams
2347 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002348 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002349 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002350
2351 // C++0x [temp.deduct.conv]p4:
2352 // In general, the deduction process attempts to find template
2353 // argument values that will make the deduced A identical to
2354 // A. However, there are two cases that allow a difference:
2355 unsigned TDF = 0;
2356 // - If the original A is a reference type, A can be more
2357 // cv-qualified than the deduced A (i.e., the type referred to
2358 // by the reference)
2359 if (ToType->isReferenceType())
2360 TDF |= TDF_ParamWithReferenceType;
2361 // - The deduced A can be another pointer or pointer to member
2362 // type that can be converted to A via a qualification
2363 // conversion.
2364 //
2365 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2366 // both P and A are pointers or member pointers. In this case, we
2367 // just ignore cv-qualifiers completely).
2368 if ((P->isPointerType() && A->isPointerType()) ||
2369 (P->isMemberPointerType() && P->isMemberPointerType()))
2370 TDF |= TDF_IgnoreQualifiers;
2371 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002372 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002373 P, A, Info, Deduced, TDF))
2374 return Result;
2375
2376 // FIXME: we need to check that the deduced A is the same as A,
2377 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002379 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002380 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002381 FunctionDecl *Spec = 0;
2382 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002383 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2384 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002385 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2386 return Result;
2387}
2388
Douglas Gregor4b52e252009-12-21 23:17:24 +00002389/// \brief Deduce template arguments for a function template when there is
2390/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2391///
2392/// \param FunctionTemplate the function template for which we are performing
2393/// template argument deduction.
2394///
2395/// \param ExplicitTemplateArguments the explicitly-specified template
2396/// arguments.
2397///
2398/// \param Specialization if template argument deduction was successful,
2399/// this will be set to the function template specialization produced by
2400/// template argument deduction.
2401///
2402/// \param Info the argument will be updated to provide additional information
2403/// about template argument deduction.
2404///
2405/// \returns the result of template argument deduction.
2406Sema::TemplateDeductionResult
2407Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2408 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2409 FunctionDecl *&Specialization,
2410 TemplateDeductionInfo &Info) {
2411 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2412 QualType(), Specialization, Info);
2413}
2414
Douglas Gregor8a514912009-09-14 18:39:43 +00002415/// \brief Stores the result of comparing the qualifiers of two types.
2416enum DeductionQualifierComparison {
2417 NeitherMoreQualified = 0,
2418 ParamMoreQualified,
2419 ArgMoreQualified
2420};
2421
2422/// \brief Deduce the template arguments during partial ordering by comparing
2423/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2424///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002425/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002426///
2427/// \param TemplateParams the template parameters that we are deducing
2428///
2429/// \param ParamIn the parameter type
2430///
2431/// \param ArgIn the argument type
2432///
2433/// \param Info information about the template argument deduction itself
2434///
2435/// \param Deduced the deduced template arguments
2436///
2437/// \returns the result of template argument deduction so far. Note that a
2438/// "success" result means that template argument deduction has not yet failed,
2439/// but it may still fail, later, for other reasons.
2440static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002441DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002442 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002443 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002444 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002445 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2446 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002447 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2448 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002449
2450 // C++0x [temp.deduct.partial]p5:
2451 // Before the partial ordering is done, certain transformations are
2452 // performed on the types used for partial ordering:
2453 // - If P is a reference type, P is replaced by the type referred to.
2454 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002455 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002456 Param = ParamRef->getPointeeType();
2457
2458 // - If A is a reference type, A is replaced by the type referred to.
2459 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002460 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002461 Arg = ArgRef->getPointeeType();
2462
John McCalle27ec8a2009-10-23 23:03:21 +00002463 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002464 // C++0x [temp.deduct.partial]p6:
2465 // If both P and A were reference types (before being replaced with the
2466 // type referred to above), determine which of the two types (if any) is
2467 // more cv-qualified than the other; otherwise the types are considered to
2468 // be equally cv-qualified for partial ordering purposes. The result of this
2469 // determination will be used below.
2470 //
2471 // We save this information for later, using it only when deduction
2472 // succeeds in both directions.
2473 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2474 if (Param.isMoreQualifiedThan(Arg))
2475 QualifierResult = ParamMoreQualified;
2476 else if (Arg.isMoreQualifiedThan(Param))
2477 QualifierResult = ArgMoreQualified;
2478 QualifierComparisons->push_back(QualifierResult);
2479 }
2480
2481 // C++0x [temp.deduct.partial]p7:
2482 // Remove any top-level cv-qualifiers:
2483 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2484 // version of P.
2485 Param = Param.getUnqualifiedType();
2486 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2487 // version of A.
2488 Arg = Arg.getUnqualifiedType();
2489
2490 // C++0x [temp.deduct.partial]p8:
2491 // Using the resulting types P and A the deduction is then done as
2492 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2493 // from the argument template is considered to be at least as specialized
2494 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002495 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002496 Deduced, TDF_None);
2497}
2498
2499static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002500MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2501 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002502 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002503 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002504
2505/// \brief If this is a non-static member function,
2506static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2507 CXXMethodDecl *Method,
2508 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2509 if (Method->isStatic())
2510 return;
2511
2512 // C++ [over.match.funcs]p4:
2513 //
2514 // For non-static member functions, the type of the implicit
2515 // object parameter is
2516 // — "lvalue reference to cv X" for functions declared without a
2517 // ref-qualifier or with the & ref-qualifier
2518 // - "rvalue reference to cv X" for functions declared with the
2519 // && ref-qualifier
2520 //
2521 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2522 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2523 ArgTy = Context.getQualifiedType(ArgTy,
2524 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2525 ArgTy = Context.getLValueReferenceType(ArgTy);
2526 ArgTypes.push_back(ArgTy);
2527}
2528
Douglas Gregor8a514912009-09-14 18:39:43 +00002529/// \brief Determine whether the function template \p FT1 is at least as
2530/// specialized as \p FT2.
2531static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002532 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002533 FunctionTemplateDecl *FT1,
2534 FunctionTemplateDecl *FT2,
2535 TemplatePartialOrderingContext TPOC,
2536 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2537 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2538 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2539 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2540 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2541
2542 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2543 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002544 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002545 Deduced.resize(TemplateParams->size());
2546
2547 // C++0x [temp.deduct.partial]p3:
2548 // The types used to determine the ordering depend on the context in which
2549 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002550 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002551 CXXMethodDecl *Method1 = 0;
2552 CXXMethodDecl *Method2 = 0;
2553 bool IsNonStatic2 = false;
2554 bool IsNonStatic1 = false;
2555 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002556 switch (TPOC) {
2557 case TPOC_Call: {
2558 // - In the context of a function call, the function parameter types are
2559 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002560 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2561 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2562 IsNonStatic1 = Method1 && !Method1->isStatic();
2563 IsNonStatic2 = Method2 && !Method2->isStatic();
2564
2565 // C++0x [temp.func.order]p3:
2566 // [...] If only one of the function templates is a non-static
2567 // member, that function template is considered to have a new
2568 // first parameter inserted in its function parameter list. The
2569 // new parameter is of type "reference to cv A," where cv are
2570 // the cv-qualifiers of the function template (if any) and A is
2571 // the class of which the function template is a member.
2572 //
2573 // C++98/03 doesn't have this provision, so instead we drop the
2574 // first argument of the free function or static member, which
2575 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002576 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002577 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2578 IsNonStatic2 && !IsNonStatic1;
2579 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002580 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2581 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002582 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002583
2584 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002585 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2586 IsNonStatic1 && !IsNonStatic2;
2587 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002588 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2589 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002590 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002591
2592 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002593 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002594 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002595 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002596 Args2[I],
2597 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002598 Info,
2599 Deduced,
2600 QualifierComparisons))
2601 return false;
2602
2603 break;
2604 }
2605
2606 case TPOC_Conversion:
2607 // - In the context of a call to a conversion operator, the return types
2608 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002609 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002610 TemplateParams,
2611 Proto2->getResultType(),
2612 Proto1->getResultType(),
2613 Info,
2614 Deduced,
2615 QualifierComparisons))
2616 return false;
2617 break;
2618
2619 case TPOC_Other:
2620 // - In other contexts (14.6.6.2) the function template’s function type
2621 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002622 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002623 TemplateParams,
2624 FD2->getType(),
2625 FD1->getType(),
2626 Info,
2627 Deduced,
2628 QualifierComparisons))
2629 return false;
2630 break;
2631 }
2632
2633 // C++0x [temp.deduct.partial]p11:
2634 // In most cases, all template parameters must have values in order for
2635 // deduction to succeed, but for partial ordering purposes a template
2636 // parameter may remain without a value provided it is not used in the
2637 // types being used for partial ordering. [ Note: a template parameter used
2638 // in a non-deduced context is considered used. -end note]
2639 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2640 for (; ArgIdx != NumArgs; ++ArgIdx)
2641 if (Deduced[ArgIdx].isNull())
2642 break;
2643
2644 if (ArgIdx == NumArgs) {
2645 // All template arguments were deduced. FT1 is at least as specialized
2646 // as FT2.
2647 return true;
2648 }
2649
Douglas Gregore73bb602009-09-14 21:25:05 +00002650 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002651 llvm::SmallVector<bool, 4> UsedParameters;
2652 UsedParameters.resize(TemplateParams->size());
2653 switch (TPOC) {
2654 case TPOC_Call: {
2655 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002656 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2657 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2658 TemplateParams->getDepth(), UsedParameters);
2659 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002660 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2661 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002662 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002663 break;
2664 }
2665
2666 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002667 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2668 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002669 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002670 break;
2671
2672 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002673 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2674 TemplateParams->getDepth(),
2675 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002676 break;
2677 }
2678
2679 for (; ArgIdx != NumArgs; ++ArgIdx)
2680 // If this argument had no value deduced but was used in one of the types
2681 // used for partial ordering, then deduction fails.
2682 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2683 return false;
2684
2685 return true;
2686}
2687
2688
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002689/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002690/// to the rules of function template partial ordering (C++ [temp.func.order]).
2691///
2692/// \param FT1 the first function template
2693///
2694/// \param FT2 the second function template
2695///
Douglas Gregor8a514912009-09-14 18:39:43 +00002696/// \param TPOC the context in which we are performing partial ordering of
2697/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002698///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002699/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002700/// template is more specialized, returns NULL.
2701FunctionTemplateDecl *
2702Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2703 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002704 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002705 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002706 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002707 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2708 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002709 &QualifierComparisons);
2710
2711 if (Better1 != Better2) // We have a clear winner
2712 return Better1? FT1 : FT2;
2713
2714 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002715 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002716
2717
2718 // C++0x [temp.deduct.partial]p10:
2719 // If for each type being considered a given template is at least as
2720 // specialized for all types and more specialized for some set of types and
2721 // the other template is not more specialized for any types or is not at
2722 // least as specialized for any types, then the given template is more
2723 // specialized than the other template. Otherwise, neither template is more
2724 // specialized than the other.
2725 Better1 = false;
2726 Better2 = false;
2727 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2728 // C++0x [temp.deduct.partial]p9:
2729 // If, for a given type, deduction succeeds in both directions (i.e., the
2730 // types are identical after the transformations above) and if the type
2731 // from the argument template is more cv-qualified than the type from the
2732 // parameter template (as described above) that type is considered to be
2733 // more specialized than the other. If neither type is more cv-qualified
2734 // than the other then neither type is more specialized than the other.
2735 switch (QualifierComparisons[I]) {
2736 case NeitherMoreQualified:
2737 break;
2738
2739 case ParamMoreQualified:
2740 Better1 = true;
2741 if (Better2)
2742 return 0;
2743 break;
2744
2745 case ArgMoreQualified:
2746 Better2 = true;
2747 if (Better1)
2748 return 0;
2749 break;
2750 }
2751 }
2752
2753 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002754 if (Better1)
2755 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002756 else if (Better2)
2757 return FT2;
2758 else
2759 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002760}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002761
Douglas Gregord5a423b2009-09-25 18:43:00 +00002762/// \brief Determine if the two templates are equivalent.
2763static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2764 if (T1 == T2)
2765 return true;
2766
2767 if (!T1 || !T2)
2768 return false;
2769
2770 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2771}
2772
2773/// \brief Retrieve the most specialized of the given function template
2774/// specializations.
2775///
John McCallc373d482010-01-27 01:50:18 +00002776/// \param SpecBegin the start iterator of the function template
2777/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002778///
John McCallc373d482010-01-27 01:50:18 +00002779/// \param SpecEnd the end iterator of the function template
2780/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002781///
2782/// \param TPOC the partial ordering context to use to compare the function
2783/// template specializations.
2784///
2785/// \param Loc the location where the ambiguity or no-specializations
2786/// diagnostic should occur.
2787///
2788/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2789/// no matching candidates.
2790///
2791/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2792/// occurs.
2793///
2794/// \param CandidateDiag partial diagnostic used for each function template
2795/// specialization that is a candidate in the ambiguous ordering. One parameter
2796/// in this diagnostic should be unbound, which will correspond to the string
2797/// describing the template arguments for the function template specialization.
2798///
2799/// \param Index if non-NULL and the result of this function is non-nULL,
2800/// receives the index corresponding to the resulting function template
2801/// specialization.
2802///
2803/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002804/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002805///
2806/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2807/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002808UnresolvedSetIterator
2809Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2810 UnresolvedSetIterator SpecEnd,
2811 TemplatePartialOrderingContext TPOC,
2812 SourceLocation Loc,
2813 const PartialDiagnostic &NoneDiag,
2814 const PartialDiagnostic &AmbigDiag,
2815 const PartialDiagnostic &CandidateDiag) {
2816 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002817 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002818 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002819 }
2820
John McCallc373d482010-01-27 01:50:18 +00002821 if (SpecBegin + 1 == SpecEnd)
2822 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002823
2824 // Find the function template that is better than all of the templates it
2825 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002826 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002827 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002828 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002829 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002830 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2831 FunctionTemplateDecl *Challenger
2832 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002833 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002834 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002835 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002836 Challenger)) {
2837 Best = I;
2838 BestTemplate = Challenger;
2839 }
2840 }
2841
2842 // Make sure that the "best" function template is more specialized than all
2843 // of the others.
2844 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002845 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2846 FunctionTemplateDecl *Challenger
2847 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002848 if (I != Best &&
2849 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002850 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002851 BestTemplate)) {
2852 Ambiguous = true;
2853 break;
2854 }
2855 }
2856
2857 if (!Ambiguous) {
2858 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002859 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002860 }
2861
2862 // Diagnose the ambiguity.
2863 Diag(Loc, AmbigDiag);
2864
2865 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002866 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2867 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002868 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002869 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2870 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002871
John McCallc373d482010-01-27 01:50:18 +00002872 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002873}
2874
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002875/// \brief Returns the more specialized class template partial specialization
2876/// according to the rules of partial ordering of class template partial
2877/// specializations (C++ [temp.class.order]).
2878///
2879/// \param PS1 the first class template partial specialization
2880///
2881/// \param PS2 the second class template partial specialization
2882///
2883/// \returns the more specialized class template partial specialization. If
2884/// neither partial specialization is more specialized, returns NULL.
2885ClassTemplatePartialSpecializationDecl *
2886Sema::getMoreSpecializedPartialSpecialization(
2887 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002888 ClassTemplatePartialSpecializationDecl *PS2,
2889 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002890 // C++ [temp.class.order]p1:
2891 // For two class template partial specializations, the first is at least as
2892 // specialized as the second if, given the following rewrite to two
2893 // function templates, the first function template is at least as
2894 // specialized as the second according to the ordering rules for function
2895 // templates (14.6.6.2):
2896 // - the first function template has the same template parameters as the
2897 // first partial specialization and has a single function parameter
2898 // whose type is a class template specialization with the template
2899 // arguments of the first partial specialization, and
2900 // - the second function template has the same template parameters as the
2901 // second partial specialization and has a single function parameter
2902 // whose type is a class template specialization with the template
2903 // arguments of the second partial specialization.
2904 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002905 // Rather than synthesize function templates, we merely perform the
2906 // equivalent partial ordering by performing deduction directly on
2907 // the template arguments of the class template partial
2908 // specializations. This computation is slightly simpler than the
2909 // general problem of function template partial ordering, because
2910 // class template partial specializations are more constrained. We
2911 // know that every template parameter is deducible from the class
2912 // template partial specialization's template arguments, for
2913 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002914 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002915 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002916
2917 QualType PT1 = PS1->getInjectedSpecializationType();
2918 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002919
2920 // Determine whether PS1 is at least as specialized as PS2
2921 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002922 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002923 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002924 PT2,
2925 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002926 Info,
2927 Deduced,
2928 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002929 if (Better1) {
2930 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2931 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002932 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2933 PS1->getTemplateArgs(),
2934 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002935 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002936
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002937 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002938 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002939 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002940 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002941 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002942 PT1,
2943 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002944 Info,
2945 Deduced,
2946 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002947 if (Better2) {
2948 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2949 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002950 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2951 PS2->getTemplateArgs(),
2952 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002953 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002954
2955 if (Better1 == Better2)
2956 return 0;
2957
2958 return Better1? PS1 : PS2;
2959}
2960
Mike Stump1eb44332009-09-09 15:08:12 +00002961static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002962MarkUsedTemplateParameters(Sema &SemaRef,
2963 const TemplateArgument &TemplateArg,
2964 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002965 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002966 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002967
Douglas Gregore73bb602009-09-14 21:25:05 +00002968/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002969/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002970static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002971MarkUsedTemplateParameters(Sema &SemaRef,
2972 const Expr *E,
2973 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002974 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002975 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00002976 // We can deduce from a pack expansion.
2977 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
2978 E = Expansion->getPattern();
2979
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002980 // Skip through any implicit casts we added while type-checking.
2981 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2982 E = ICE->getSubExpr();
2983
Douglas Gregore73bb602009-09-14 21:25:05 +00002984 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2985 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002986 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002987 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002988 return;
2989
Mike Stump1eb44332009-09-09 15:08:12 +00002990 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002991 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2992 if (!NTTP)
2993 return;
2994
Douglas Gregored9c0f92009-10-29 00:04:11 +00002995 if (NTTP->getDepth() == Depth)
2996 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002997}
2998
Douglas Gregore73bb602009-09-14 21:25:05 +00002999/// \brief Mark the template parameters that are used by the given
3000/// nested name specifier.
3001static void
3002MarkUsedTemplateParameters(Sema &SemaRef,
3003 NestedNameSpecifier *NNS,
3004 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003005 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003006 llvm::SmallVectorImpl<bool> &Used) {
3007 if (!NNS)
3008 return;
3009
Douglas Gregored9c0f92009-10-29 00:04:11 +00003010 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3011 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003012 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003013 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003014}
3015
3016/// \brief Mark the template parameters that are used by the given
3017/// template name.
3018static void
3019MarkUsedTemplateParameters(Sema &SemaRef,
3020 TemplateName Name,
3021 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003022 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003023 llvm::SmallVectorImpl<bool> &Used) {
3024 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3025 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003026 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3027 if (TTP->getDepth() == Depth)
3028 Used[TTP->getIndex()] = true;
3029 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003030 return;
3031 }
3032
Douglas Gregor788cd062009-11-11 01:00:40 +00003033 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3034 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3035 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003036 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003037 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3038 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003039}
3040
3041/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003042/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003043static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003044MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3045 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003046 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003047 llvm::SmallVectorImpl<bool> &Used) {
3048 if (T.isNull())
3049 return;
3050
Douglas Gregor031a5882009-06-13 00:26:55 +00003051 // Non-dependent types have nothing deducible
3052 if (!T->isDependentType())
3053 return;
3054
3055 T = SemaRef.Context.getCanonicalType(T);
3056 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003057 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003058 MarkUsedTemplateParameters(SemaRef,
3059 cast<PointerType>(T)->getPointeeType(),
3060 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003061 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003062 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003063 break;
3064
3065 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003066 MarkUsedTemplateParameters(SemaRef,
3067 cast<BlockPointerType>(T)->getPointeeType(),
3068 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003069 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003070 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003071 break;
3072
3073 case Type::LValueReference:
3074 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003075 MarkUsedTemplateParameters(SemaRef,
3076 cast<ReferenceType>(T)->getPointeeType(),
3077 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003078 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003079 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003080 break;
3081
3082 case Type::MemberPointer: {
3083 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003084 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003085 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003086 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003087 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003088 break;
3089 }
3090
3091 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003092 MarkUsedTemplateParameters(SemaRef,
3093 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003094 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003095 // Fall through to check the element type
3096
3097 case Type::ConstantArray:
3098 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003099 MarkUsedTemplateParameters(SemaRef,
3100 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003101 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003102 break;
3103
3104 case Type::Vector:
3105 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003106 MarkUsedTemplateParameters(SemaRef,
3107 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003108 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003109 break;
3110
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003111 case Type::DependentSizedExtVector: {
3112 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003113 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003114 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003115 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003116 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003117 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003118 break;
3119 }
3120
Douglas Gregor031a5882009-06-13 00:26:55 +00003121 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003122 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003123 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003124 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003125 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003126 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003127 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003128 break;
3129 }
3130
Douglas Gregored9c0f92009-10-29 00:04:11 +00003131 case Type::TemplateTypeParm: {
3132 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3133 if (TTP->getDepth() == Depth)
3134 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003135 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003136 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003137
John McCall31f17ec2010-04-27 00:57:59 +00003138 case Type::InjectedClassName:
3139 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3140 // fall through
3141
Douglas Gregor031a5882009-06-13 00:26:55 +00003142 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003143 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003144 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003145 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003146 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003147
3148 // C++0x [temp.deduct.type]p9:
3149 // If the template argument list of P contains a pack expansion that is not
3150 // the last template argument, the entire template argument list is a
3151 // non-deduced context.
3152 if (OnlyDeduced &&
3153 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3154 break;
3155
Douglas Gregore73bb602009-09-14 21:25:05 +00003156 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003157 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3158 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003159 break;
3160 }
3161
Douglas Gregore73bb602009-09-14 21:25:05 +00003162 case Type::Complex:
3163 if (!OnlyDeduced)
3164 MarkUsedTemplateParameters(SemaRef,
3165 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003166 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003167 break;
3168
Douglas Gregor4714c122010-03-31 17:34:00 +00003169 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003170 if (!OnlyDeduced)
3171 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003172 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003173 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003174 break;
3175
John McCall33500952010-06-11 00:33:02 +00003176 case Type::DependentTemplateSpecialization: {
3177 const DependentTemplateSpecializationType *Spec
3178 = cast<DependentTemplateSpecializationType>(T);
3179 if (!OnlyDeduced)
3180 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3181 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003182
3183 // C++0x [temp.deduct.type]p9:
3184 // If the template argument list of P contains a pack expansion that is not
3185 // the last template argument, the entire template argument list is a
3186 // non-deduced context.
3187 if (OnlyDeduced &&
3188 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3189 break;
3190
John McCall33500952010-06-11 00:33:02 +00003191 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3192 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3193 Used);
3194 break;
3195 }
3196
John McCallad5e7382010-03-01 23:49:17 +00003197 case Type::TypeOf:
3198 if (!OnlyDeduced)
3199 MarkUsedTemplateParameters(SemaRef,
3200 cast<TypeOfType>(T)->getUnderlyingType(),
3201 OnlyDeduced, Depth, Used);
3202 break;
3203
3204 case Type::TypeOfExpr:
3205 if (!OnlyDeduced)
3206 MarkUsedTemplateParameters(SemaRef,
3207 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3208 OnlyDeduced, Depth, Used);
3209 break;
3210
3211 case Type::Decltype:
3212 if (!OnlyDeduced)
3213 MarkUsedTemplateParameters(SemaRef,
3214 cast<DecltypeType>(T)->getUnderlyingExpr(),
3215 OnlyDeduced, Depth, Used);
3216 break;
3217
Douglas Gregor7536dd52010-12-20 02:24:11 +00003218 case Type::PackExpansion:
3219 MarkUsedTemplateParameters(SemaRef,
3220 cast<PackExpansionType>(T)->getPattern(),
3221 OnlyDeduced, Depth, Used);
3222 break;
3223
Douglas Gregore73bb602009-09-14 21:25:05 +00003224 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003225 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003226 case Type::VariableArray:
3227 case Type::FunctionNoProto:
3228 case Type::Record:
3229 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003230 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003231 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003232 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003233 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003234#define TYPE(Class, Base)
3235#define ABSTRACT_TYPE(Class, Base)
3236#define DEPENDENT_TYPE(Class, Base)
3237#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3238#include "clang/AST/TypeNodes.def"
3239 break;
3240 }
3241}
3242
Douglas Gregore73bb602009-09-14 21:25:05 +00003243/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003244/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003245static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003246MarkUsedTemplateParameters(Sema &SemaRef,
3247 const TemplateArgument &TemplateArg,
3248 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003249 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003250 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003251 switch (TemplateArg.getKind()) {
3252 case TemplateArgument::Null:
3253 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003254 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003255 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Douglas Gregor031a5882009-06-13 00:26:55 +00003257 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003258 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003259 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003260 break;
3261
Douglas Gregor788cd062009-11-11 01:00:40 +00003262 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003263 case TemplateArgument::TemplateExpansion:
3264 MarkUsedTemplateParameters(SemaRef,
3265 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003266 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003267 break;
3268
3269 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003270 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003271 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003272 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003273
Anders Carlssond01b1da2009-06-15 17:04:53 +00003274 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003275 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3276 PEnd = TemplateArg.pack_end();
3277 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003278 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003279 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003280 }
3281}
3282
3283/// \brief Mark the template parameters can be deduced by the given
3284/// template argument list.
3285///
3286/// \param TemplateArgs the template argument list from which template
3287/// parameters will be deduced.
3288///
3289/// \param Deduced a bit vector whose elements will be set to \c true
3290/// to indicate when the corresponding template parameter will be
3291/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003292void
Douglas Gregore73bb602009-09-14 21:25:05 +00003293Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003294 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003295 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003296 // C++0x [temp.deduct.type]p9:
3297 // If the template argument list of P contains a pack expansion that is not
3298 // the last template argument, the entire template argument list is a
3299 // non-deduced context.
3300 if (OnlyDeduced &&
3301 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3302 return;
3303
Douglas Gregor031a5882009-06-13 00:26:55 +00003304 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003305 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3306 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003307}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003308
3309/// \brief Marks all of the template parameters that will be deduced by a
3310/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003311void
3312Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3313 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003314 TemplateParameterList *TemplateParams
3315 = FunctionTemplate->getTemplateParameters();
3316 Deduced.clear();
3317 Deduced.resize(TemplateParams->size());
3318
3319 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3320 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3321 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003322 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003323}