blob: e762d341176b26dedf26d995a0d64f2bd8225d33 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregor603cfb42011-01-05 23:12:31 +0000481/// \brief Retrieve the depth and index of an unexpanded parameter pack.
482static std::pair<unsigned, unsigned>
483getDepthAndIndex(UnexpandedParameterPack UPP) {
484 if (const TemplateTypeParmType *TTP
485 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
486 return std::make_pair(TTP->getDepth(), TTP->getIndex());
487
488 NamedDecl *ND = UPP.first.get<NamedDecl *>();
489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
490 return std::make_pair(TTP->getDepth(), TTP->getIndex());
491
492 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
493 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
494
495 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
496 return std::make_pair(TTP->getDepth(), TTP->getIndex());
497}
498
499/// \brief Helper function to build a TemplateParameter when we don't
500/// know its type statically.
501static TemplateParameter makeTemplateParameter(Decl *D) {
502 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
503 return TemplateParameter(TTP);
504 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
505 return TemplateParameter(NTTP);
506
507 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
508}
509
510/// \brief Deduce the template arguments by comparing the list of parameter
511/// types to the list of argument types, as in the parameter-type-lists of
512/// function types (C++ [temp.deduct.type]p10).
513///
514/// \param S The semantic analysis object within which we are deducing
515///
516/// \param TemplateParams The template parameters that we are deducing
517///
518/// \param Params The list of parameter types
519///
520/// \param NumParams The number of types in \c Params
521///
522/// \param Args The list of argument types
523///
524/// \param NumArgs The number of types in \c Args
525///
526/// \param Info information about the template argument deduction itself
527///
528/// \param Deduced the deduced template arguments
529///
530/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
531/// how template argument deduction is performed.
532///
533/// \returns the result of template argument deduction so far. Note that a
534/// "success" result means that template argument deduction has not yet failed,
535/// but it may still fail, later, for other reasons.
536static Sema::TemplateDeductionResult
537DeduceTemplateArguments(Sema &S,
538 TemplateParameterList *TemplateParams,
539 const QualType *Params, unsigned NumParams,
540 const QualType *Args, unsigned NumArgs,
541 TemplateDeductionInfo &Info,
542 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
543 unsigned TDF) {
544 // FIXME: Fast-path check with NumParams != NumArgs and there are no
545 // pack expansions around.
546
547 // C++0x [temp.deduct.type]p10:
548 // Similarly, if P has a form that contains (T), then each parameter type
549 // Pi of the respective parameter-type- list of P is compared with the
550 // corresponding parameter type Ai of the corresponding parameter-type-list
551 // of A. [...]
552 unsigned ArgIdx = 0, ParamIdx = 0;
553 for (; ParamIdx != NumParams; ++ParamIdx) {
554 // Check argument types.
555 const PackExpansionType *Expansion
556 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
557 if (!Expansion) {
558 // Simple case: compare the parameter and argument types at this point.
559
560 // Make sure we have an argument.
561 if (ArgIdx >= NumArgs)
562 return Sema::TDK_TooFewArguments;
563
564 if (Sema::TemplateDeductionResult Result
565 = DeduceTemplateArguments(S, TemplateParams,
566 Params[ParamIdx],
567 Args[ArgIdx],
568 Info, Deduced, TDF))
569 return Result;
570
571 ++ArgIdx;
572 continue;
573 }
574
575 // C++0x [temp.deduct.type]p10:
576 // If the parameter-declaration corresponding to Pi is a function
577 // parameter pack, then the type of its declarator- id is compared with
578 // each remaining parameter type in the parameter-type-list of A. Each
579 // comparison deduces template arguments for subsequent positions in the
580 // template parameter packs expanded by the function parameter pack.
581
582 // Compute the set of template parameter indices that correspond to
583 // parameter packs expanded by the pack expansion.
584 llvm::SmallVector<unsigned, 2> PackIndices;
585 QualType Pattern = Expansion->getPattern();
586 {
587 llvm::BitVector SawIndices(TemplateParams->size());
588 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
589 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
590 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
591 unsigned Depth, Index;
592 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
593 if (Depth == 0 && !SawIndices[Index]) {
594 SawIndices[Index] = true;
595 PackIndices.push_back(Index);
596 }
597 }
598 }
599 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
600
601 // Save the deduced template arguments for each parameter pack expanded
602 // by this pack expansion, then clear out the deduction.
603 llvm::SmallVector<DeducedTemplateArgument, 2>
604 SavedPacks(PackIndices.size());
605 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
606 SavedPacks[I] = Deduced[PackIndices[I]];
607 Deduced[PackIndices[I]] = DeducedTemplateArgument();
608 }
609
610 // Keep track of the deduced template arguments for each parameter pack
611 // expanded by this pack expansion (the outer index) and for each
612 // template argument (the inner SmallVectors).
613 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
614 NewlyDeducedPacks(PackIndices.size());
615 bool HasAnyArguments = false;
616 for (; ArgIdx < NumArgs; ++ArgIdx) {
617 HasAnyArguments = true;
618
619 // Deduce template arguments from the pattern.
620 if (Sema::TemplateDeductionResult Result
621 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
622 Info, Deduced))
623 return Result;
624
625 // Capture the deduced template arguments for each parameter pack expanded
626 // by this pack expansion, add them to the list of arguments we've deduced
627 // for that pack, then clear out the deduced argument.
628 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
629 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
630 if (!DeducedArg.isNull()) {
631 NewlyDeducedPacks[I].push_back(DeducedArg);
632 DeducedArg = DeducedTemplateArgument();
633 }
634 }
635 }
636
637 // Build argument packs for each of the parameter packs expanded by this
638 // pack expansion.
639 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
640 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
641 // We were not able to deduce anything for this parameter pack,
642 // so just restore the saved argument pack.
643 Deduced[PackIndices[I]] = SavedPacks[I];
644 continue;
645 }
646
647 DeducedTemplateArgument NewPack;
648
649 if (NewlyDeducedPacks[I].empty()) {
650 // If we deduced an empty argument pack, create it now.
651 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
652 } else {
653 TemplateArgument *ArgumentPack
654 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
655 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
656 ArgumentPack);
657 NewPack
658 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
659 NewlyDeducedPacks[I].size()),
660 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
661 }
662
663 DeducedTemplateArgument Result
664 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
665 if (Result.isNull()) {
666 Info.Param
667 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
668 Info.FirstArg = SavedPacks[I];
669 Info.SecondArg = NewPack;
670 return Sema::TDK_Inconsistent;
671 }
672
673 Deduced[PackIndices[I]] = Result;
674 }
675 }
676
677 // Make sure we don't have any extra arguments.
678 if (ArgIdx < NumArgs)
679 return Sema::TDK_TooManyArguments;
680
681 return Sema::TDK_Success;
682}
683
Douglas Gregor500d3312009-06-26 18:27:22 +0000684/// \brief Deduce the template arguments by comparing the parameter type and
685/// the argument type (C++ [temp.deduct.type]).
686///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000687/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000688///
689/// \param TemplateParams the template parameters that we are deducing
690///
691/// \param ParamIn the parameter type
692///
693/// \param ArgIn the argument type
694///
695/// \param Info information about the template argument deduction itself
696///
697/// \param Deduced the deduced template arguments
698///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000699/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000700/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000701///
702/// \returns the result of template argument deduction so far. Note that a
703/// "success" result means that template argument deduction has not yet failed,
704/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000705static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000706DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000707 TemplateParameterList *TemplateParams,
708 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000709 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000710 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000711 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000712 // We only want to look at the canonical types, since typedefs and
713 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000714 QualType Param = S.Context.getCanonicalType(ParamIn);
715 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000716
Douglas Gregor500d3312009-06-26 18:27:22 +0000717 // C++0x [temp.deduct.call]p4 bullet 1:
718 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000719 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000720 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000721 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000722 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000723 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000724 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
725 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000726 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000727 }
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000729 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000730 if (!Param->isDependentType()) {
731 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
732
733 return Sema::TDK_NonDeducedMismatch;
734 }
735
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000736 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000737 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000738
Douglas Gregor199d9912009-06-05 00:53:49 +0000739 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000740 // A template type argument T, a template template argument TT or a
741 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000742 // the following forms:
743 //
744 // T
745 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000746 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000747 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000748 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000749 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000751 // If the argument type is an array type, move the qualifiers up to the
752 // top level, so they can be matched with the qualifiers on the parameter.
753 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000754 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000755 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000756 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000757 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000758 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000759 RecanonicalizeArg = true;
760 }
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000763 // The argument type can not be less qualified than the parameter
764 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000765 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000766 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000767 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000768 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000769 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000770 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000771
772 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000773 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000774 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000775
776 // local manipulation is okay because it's canonical
777 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000778 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000779 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000781 DeducedTemplateArgument NewDeduced(DeducedType);
782 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
783 Deduced[Index],
784 NewDeduced);
785 if (Result.isNull()) {
786 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
787 Info.FirstArg = Deduced[Index];
788 Info.SecondArg = NewDeduced;
789 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000790 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000791
792 Deduced[Index] = Result;
793 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000794 }
795
Douglas Gregorf67875d2009-06-12 18:26:56 +0000796 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000797 Info.FirstArg = TemplateArgument(ParamIn);
798 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000799
Douglas Gregor508f1c82009-06-26 23:10:12 +0000800 // Check the cv-qualifiers on the parameter and argument types.
801 if (!(TDF & TDF_IgnoreQualifiers)) {
802 if (TDF & TDF_ParamWithReferenceType) {
803 if (Param.isMoreQualifiedThan(Arg))
804 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000805 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000806 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000807 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000808 }
809 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000810
Douglas Gregord560d502009-06-04 00:21:18 +0000811 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000812 // No deduction possible for these types
813 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000814 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Douglas Gregor199d9912009-06-05 00:53:49 +0000816 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000817 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000818 QualType PointeeType;
819 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
820 PointeeType = PointerArg->getPointeeType();
821 } else if (const ObjCObjectPointerType *PointerArg
822 = Arg->getAs<ObjCObjectPointerType>()) {
823 PointeeType = PointerArg->getPointeeType();
824 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000825 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregor41128772009-06-26 23:27:24 +0000828 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000829 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000830 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000831 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000832 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000833 }
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregor199d9912009-06-05 00:53:49 +0000835 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000836 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000837 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000838 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000839 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000841 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000842 cast<LValueReferenceType>(Param)->getPointeeType(),
843 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000844 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000845 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000846
Douglas Gregor199d9912009-06-05 00:53:49 +0000847 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000848 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000849 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000850 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000851 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000853 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000854 cast<RValueReferenceType>(Param)->getPointeeType(),
855 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000856 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregor199d9912009-06-05 00:53:49 +0000859 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000860 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000861 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000862 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000863 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000864 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
John McCalle4f26e52010-08-19 00:20:19 +0000866 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000867 return DeduceTemplateArguments(S, TemplateParams,
868 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000869 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000870 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000871 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000872
873 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000874 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000875 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000876 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000877 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000878 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000879
880 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000881 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000882 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000883 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
John McCalle4f26e52010-08-19 00:20:19 +0000885 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000886 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000887 ConstantArrayParm->getElementType(),
888 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000889 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000890 }
891
Douglas Gregor199d9912009-06-05 00:53:49 +0000892 // type [i]
893 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000894 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000896 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
John McCalle4f26e52010-08-19 00:20:19 +0000898 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
899
Douglas Gregor199d9912009-06-05 00:53:49 +0000900 // Check the element type of the arrays
901 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000902 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000903 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000904 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000905 DependentArrayParm->getElementType(),
906 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000907 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000908 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Douglas Gregor199d9912009-06-05 00:53:49 +0000910 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000911 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000912 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
913 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000914 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000915
916 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000917 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000918 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000919 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000920 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000921 = dyn_cast<ConstantArrayType>(ArrayArg)) {
922 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000923 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
924 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000925 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000926 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000927 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000928 if (const DependentSizedArrayType *DependentArrayArg
929 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000930 if (DependentArrayArg->getSizeExpr())
931 return DeduceNonTypeTemplateArgument(S, NTTP,
932 DependentArrayArg->getSizeExpr(),
933 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregor199d9912009-06-05 00:53:49 +0000935 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000936 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
939 // type(*)(T)
940 // T(*)()
941 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000942 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000943 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000944 dyn_cast<FunctionProtoType>(Arg);
945 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000946 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
948 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000949 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000950
Mike Stump1eb44332009-09-09 15:08:12 +0000951 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000952 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000953 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000955 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000956 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000957
Anders Carlssona27fad52009-06-08 15:19:08 +0000958 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000959 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000960 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000961 FunctionProtoParam->getResultType(),
962 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000963 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000964 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregor603cfb42011-01-05 23:12:31 +0000966 return DeduceTemplateArguments(S, TemplateParams,
967 FunctionProtoParam->arg_type_begin(),
968 FunctionProtoParam->getNumArgs(),
969 FunctionProtoArg->arg_type_begin(),
970 FunctionProtoArg->getNumArgs(),
971 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +0000972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
John McCall3cb0ebd2010-03-10 03:28:59 +0000974 case Type::InjectedClassName: {
975 // Treat a template's injected-class-name as if the template
976 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000977 Param = cast<InjectedClassNameType>(Param)
978 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000979 assert(isa<TemplateSpecializationType>(Param) &&
980 "injected class name is not a template specialization type");
981 // fall through
982 }
983
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000984 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000985 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000986 // TT<T>
987 // TT<i>
988 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000989 case Type::TemplateSpecialization: {
990 const TemplateSpecializationType *SpecParam
991 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000993 // Try to deduce template arguments from the template-id.
994 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000995 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000996 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000998 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000999 // C++ [temp.deduct.call]p3b3:
1000 // If P is a class, and P has the form template-id, then A can be a
1001 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001002 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001003 // class pointed to by the deduced A.
1004 //
1005 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001006 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001007 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001008 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1009 // We cannot inspect base classes as part of deduction when the type
1010 // is incomplete, so either instantiate any templates necessary to
1011 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001012 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001013 return Result;
1014
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001015 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001016 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001017 // ToVisit is our stack of records that we still need to visit.
1018 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1019 llvm::SmallVector<const RecordType *, 8> ToVisit;
1020 ToVisit.push_back(RecordT);
1021 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001022 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1023 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001024 while (!ToVisit.empty()) {
1025 // Retrieve the next class in the inheritance hierarchy.
1026 const RecordType *NextT = ToVisit.back();
1027 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001029 // If we have already seen this type, skip it.
1030 if (!Visited.insert(NextT))
1031 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001033 // If this is a base class, try to perform template argument
1034 // deduction from it.
1035 if (NextT != RecordT) {
1036 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001037 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001038 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001040 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001041 // note that we had some success. Otherwise, ignore any deductions
1042 // from this base class.
1043 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001044 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001045 DeducedOrig = Deduced;
1046 }
1047 else
1048 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001051 // Visit base classes
1052 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1053 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1054 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001055 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001056 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001057 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001059 }
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001062 if (Successful)
1063 return Sema::TDK_Success;
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001068 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001069 }
1070
Douglas Gregor637a4092009-06-10 23:47:09 +00001071 // T type::*
1072 // T T::*
1073 // T (type::*)()
1074 // type (T::*)()
1075 // type (type::*)(T)
1076 // type (T::*)(T)
1077 // T (type::*)(T)
1078 // T (T::*)()
1079 // T (T::*)(T)
1080 case Type::MemberPointer: {
1081 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1082 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1083 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001084 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001085
Douglas Gregorf67875d2009-06-12 18:26:56 +00001086 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001087 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001088 MemPtrParam->getPointeeType(),
1089 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001090 Info, Deduced,
1091 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001092 return Result;
1093
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001094 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001095 QualType(MemPtrParam->getClass(), 0),
1096 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001097 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001098 }
1099
Anders Carlsson9a917e42009-06-12 22:56:54 +00001100 // (clang extension)
1101 //
Mike Stump1eb44332009-09-09 15:08:12 +00001102 // type(^)(T)
1103 // T(^)()
1104 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001105 case Type::BlockPointer: {
1106 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1107 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Anders Carlsson859ba502009-06-12 16:23:10 +00001109 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001110 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001112 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001113 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001114 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001115 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001116 }
1117
Douglas Gregor637a4092009-06-10 23:47:09 +00001118 case Type::TypeOfExpr:
1119 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001120 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001121 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001122 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001123
Douglas Gregord560d502009-06-04 00:21:18 +00001124 default:
1125 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001126 }
1127
1128 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001129 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001130}
1131
Douglas Gregorf67875d2009-06-12 18:26:56 +00001132static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001133DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001134 TemplateParameterList *TemplateParams,
1135 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001136 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001137 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001138 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001139 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001140 case TemplateArgument::Null:
1141 assert(false && "Null template argument in parameter list");
1142 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
1144 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001145 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001146 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001147 Arg.getAsType(), Info, Deduced, 0);
1148 Info.FirstArg = Param;
1149 Info.SecondArg = Arg;
1150 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001151
Douglas Gregor788cd062009-11-11 01:00:40 +00001152 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001153 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001154 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001155 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001156 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001157 Info.FirstArg = Param;
1158 Info.SecondArg = Arg;
1159 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001160
1161 case TemplateArgument::TemplateExpansion:
1162 llvm_unreachable("caller should handle pack expansions");
1163 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001164
Douglas Gregor199d9912009-06-05 00:53:49 +00001165 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001166 if (Arg.getKind() == TemplateArgument::Declaration &&
1167 Param.getAsDecl()->getCanonicalDecl() ==
1168 Arg.getAsDecl()->getCanonicalDecl())
1169 return Sema::TDK_Success;
1170
Douglas Gregorf67875d2009-06-12 18:26:56 +00001171 Info.FirstArg = Param;
1172 Info.SecondArg = Arg;
1173 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Douglas Gregor199d9912009-06-05 00:53:49 +00001175 case TemplateArgument::Integral:
1176 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001177 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001178 return Sema::TDK_Success;
1179
1180 Info.FirstArg = Param;
1181 Info.SecondArg = Arg;
1182 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001183 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001184
1185 if (Arg.getKind() == TemplateArgument::Expression) {
1186 Info.FirstArg = Param;
1187 Info.SecondArg = Arg;
1188 return Sema::TDK_NonDeducedMismatch;
1189 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001190
Douglas Gregorf67875d2009-06-12 18:26:56 +00001191 Info.FirstArg = Param;
1192 Info.SecondArg = Arg;
1193 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Douglas Gregor199d9912009-06-05 00:53:49 +00001195 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001196 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001197 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1198 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001199 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001200 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001201 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001202 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001203 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001204 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001205 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001206 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001207 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001208 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001209 Info, Deduced);
1210
Douglas Gregorf67875d2009-06-12 18:26:56 +00001211 Info.FirstArg = Param;
1212 Info.SecondArg = Arg;
1213 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Douglas Gregor199d9912009-06-05 00:53:49 +00001216 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001217 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001218 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001219 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001220 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001221 }
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Douglas Gregorf67875d2009-06-12 18:26:56 +00001223 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001224}
1225
Douglas Gregor20a55e22010-12-22 18:17:10 +00001226/// \brief Determine whether there is a template argument to be used for
1227/// deduction.
1228///
1229/// This routine "expands" argument packs in-place, overriding its input
1230/// parameters so that \c Args[ArgIdx] will be the available template argument.
1231///
1232/// \returns true if there is another template argument (which will be at
1233/// \c Args[ArgIdx]), false otherwise.
1234static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1235 unsigned &ArgIdx,
1236 unsigned &NumArgs) {
1237 if (ArgIdx == NumArgs)
1238 return false;
1239
1240 const TemplateArgument &Arg = Args[ArgIdx];
1241 if (Arg.getKind() != TemplateArgument::Pack)
1242 return true;
1243
1244 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1245 Args = Arg.pack_begin();
1246 NumArgs = Arg.pack_size();
1247 ArgIdx = 0;
1248 return ArgIdx < NumArgs;
1249}
1250
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001251/// \brief Determine whether the given set of template arguments has a pack
1252/// expansion that is not the last template argument.
1253static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1254 unsigned NumArgs) {
1255 unsigned ArgIdx = 0;
1256 while (ArgIdx < NumArgs) {
1257 const TemplateArgument &Arg = Args[ArgIdx];
1258
1259 // Unwrap argument packs.
1260 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1261 Args = Arg.pack_begin();
1262 NumArgs = Arg.pack_size();
1263 ArgIdx = 0;
1264 continue;
1265 }
1266
1267 ++ArgIdx;
1268 if (ArgIdx == NumArgs)
1269 return false;
1270
1271 if (Arg.isPackExpansion())
1272 return true;
1273 }
1274
1275 return false;
1276}
1277
Douglas Gregor20a55e22010-12-22 18:17:10 +00001278static Sema::TemplateDeductionResult
1279DeduceTemplateArguments(Sema &S,
1280 TemplateParameterList *TemplateParams,
1281 const TemplateArgument *Params, unsigned NumParams,
1282 const TemplateArgument *Args, unsigned NumArgs,
1283 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001284 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1285 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001286 // C++0x [temp.deduct.type]p9:
1287 // If the template argument list of P contains a pack expansion that is not
1288 // the last template argument, the entire template argument list is a
1289 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001290 if (hasPackExpansionBeforeEnd(Params, NumParams))
1291 return Sema::TDK_Success;
1292
Douglas Gregore02e2622010-12-22 21:19:48 +00001293 // C++0x [temp.deduct.type]p9:
1294 // If P has a form that contains <T> or <i>, then each argument Pi of the
1295 // respective template argument list P is compared with the corresponding
1296 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001297 unsigned ArgIdx = 0, ParamIdx = 0;
1298 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1299 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001300 // FIXME: Variadic templates.
1301 // What do we do if the argument is a pack expansion?
1302
Douglas Gregor20a55e22010-12-22 18:17:10 +00001303 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001304 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001305
1306 // Check whether we have enough arguments.
1307 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001308 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1309 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001310
Douglas Gregore02e2622010-12-22 21:19:48 +00001311 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001312 if (Sema::TemplateDeductionResult Result
1313 = DeduceTemplateArguments(S, TemplateParams,
1314 Params[ParamIdx], Args[ArgIdx],
1315 Info, Deduced))
1316 return Result;
1317
1318 // Move to the next argument.
1319 ++ArgIdx;
1320 continue;
1321 }
1322
Douglas Gregore02e2622010-12-22 21:19:48 +00001323 // The parameter is a pack expansion.
1324
1325 // C++0x [temp.deduct.type]p9:
1326 // If Pi is a pack expansion, then the pattern of Pi is compared with
1327 // each remaining argument in the template argument list of A. Each
1328 // comparison deduces template arguments for subsequent positions in the
1329 // template parameter packs expanded by Pi.
1330 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1331
1332 // Compute the set of template parameter indices that correspond to
1333 // parameter packs expanded by the pack expansion.
1334 llvm::SmallVector<unsigned, 2> PackIndices;
1335 {
1336 llvm::BitVector SawIndices(TemplateParams->size());
1337 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1338 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1339 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1340 unsigned Depth, Index;
1341 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1342 if (Depth == 0 && !SawIndices[Index]) {
1343 SawIndices[Index] = true;
1344 PackIndices.push_back(Index);
1345 }
1346 }
1347 }
1348 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1349
1350 // FIXME: If there are no remaining arguments, we can bail out early
1351 // and set any deduced parameter packs to an empty argument pack.
1352 // The latter part of this is a (minor) correctness issue.
1353
1354 // Save the deduced template arguments for each parameter pack expanded
1355 // by this pack expansion, then clear out the deduction.
1356 llvm::SmallVector<DeducedTemplateArgument, 2>
1357 SavedPacks(PackIndices.size());
1358 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1359 SavedPacks[I] = Deduced[PackIndices[I]];
1360 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1361 }
1362
1363 // Keep track of the deduced template arguments for each parameter pack
1364 // expanded by this pack expansion (the outer index) and for each
1365 // template argument (the inner SmallVectors).
1366 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1367 NewlyDeducedPacks(PackIndices.size());
1368 bool HasAnyArguments = false;
1369 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1370 HasAnyArguments = true;
1371
1372 // Deduce template arguments from the pattern.
1373 if (Sema::TemplateDeductionResult Result
1374 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1375 Info, Deduced))
1376 return Result;
1377
1378 // Capture the deduced template arguments for each parameter pack expanded
1379 // by this pack expansion, add them to the list of arguments we've deduced
1380 // for that pack, then clear out the deduced argument.
1381 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1382 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1383 if (!DeducedArg.isNull()) {
1384 NewlyDeducedPacks[I].push_back(DeducedArg);
1385 DeducedArg = DeducedTemplateArgument();
1386 }
1387 }
1388
1389 ++ArgIdx;
1390 }
1391
1392 // Build argument packs for each of the parameter packs expanded by this
1393 // pack expansion.
1394 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1395 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1396 // We were not able to deduce anything for this parameter pack,
1397 // so just restore the saved argument pack.
1398 Deduced[PackIndices[I]] = SavedPacks[I];
1399 continue;
1400 }
1401
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001402 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001403
1404 if (NewlyDeducedPacks[I].empty()) {
1405 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001406 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1407 } else {
1408 TemplateArgument *ArgumentPack
1409 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1410 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1411 ArgumentPack);
1412 NewPack
1413 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001414 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001415 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1416 }
1417
1418 DeducedTemplateArgument Result
1419 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1420 if (Result.isNull()) {
1421 Info.Param
1422 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1423 Info.FirstArg = SavedPacks[I];
1424 Info.SecondArg = NewPack;
1425 return Sema::TDK_Inconsistent;
1426 }
1427
1428 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001429 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001430 }
1431
1432 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001433 if (NumberOfArgumentsMustMatch &&
1434 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001435 return Sema::TDK_TooManyArguments;
1436
1437 return Sema::TDK_Success;
1438}
1439
Mike Stump1eb44332009-09-09 15:08:12 +00001440static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001441DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001442 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001443 const TemplateArgumentList &ParamList,
1444 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001445 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001446 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001447 return DeduceTemplateArguments(S, TemplateParams,
1448 ParamList.data(), ParamList.size(),
1449 ArgList.data(), ArgList.size(),
1450 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001451}
1452
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001453/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001454static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001455 const TemplateArgument &X,
1456 const TemplateArgument &Y) {
1457 if (X.getKind() != Y.getKind())
1458 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001460 switch (X.getKind()) {
1461 case TemplateArgument::Null:
1462 assert(false && "Comparing NULL template argument");
1463 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001465 case TemplateArgument::Type:
1466 return Context.getCanonicalType(X.getAsType()) ==
1467 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001469 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001470 return X.getAsDecl()->getCanonicalDecl() ==
1471 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Douglas Gregor788cd062009-11-11 01:00:40 +00001473 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001474 case TemplateArgument::TemplateExpansion:
1475 return Context.getCanonicalTemplateName(
1476 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1477 Context.getCanonicalTemplateName(
1478 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001479
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001480 case TemplateArgument::Integral:
1481 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Douglas Gregor788cd062009-11-11 01:00:40 +00001483 case TemplateArgument::Expression: {
1484 llvm::FoldingSetNodeID XID, YID;
1485 X.getAsExpr()->Profile(XID, Context, true);
1486 Y.getAsExpr()->Profile(YID, Context, true);
1487 return XID == YID;
1488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001490 case TemplateArgument::Pack:
1491 if (X.pack_size() != Y.pack_size())
1492 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001493
1494 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1495 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001496 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001497 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001498 if (!isSameTemplateArg(Context, *XP, *YP))
1499 return false;
1500
1501 return true;
1502 }
1503
1504 return false;
1505}
1506
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001507/// \brief Allocate a TemplateArgumentLoc where all locations have
1508/// been initialized to the given location.
1509///
1510/// \param S The semantic analysis object.
1511///
1512/// \param The template argument we are producing template argument
1513/// location information for.
1514///
1515/// \param NTTPType For a declaration template argument, the type of
1516/// the non-type template parameter that corresponds to this template
1517/// argument.
1518///
1519/// \param Loc The source location to use for the resulting template
1520/// argument.
1521static TemplateArgumentLoc
1522getTrivialTemplateArgumentLoc(Sema &S,
1523 const TemplateArgument &Arg,
1524 QualType NTTPType,
1525 SourceLocation Loc) {
1526 switch (Arg.getKind()) {
1527 case TemplateArgument::Null:
1528 llvm_unreachable("Can't get a NULL template argument here");
1529 break;
1530
1531 case TemplateArgument::Type:
1532 return TemplateArgumentLoc(Arg,
1533 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1534
1535 case TemplateArgument::Declaration: {
1536 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001537 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001538 .takeAs<Expr>();
1539 return TemplateArgumentLoc(TemplateArgument(E), E);
1540 }
1541
1542 case TemplateArgument::Integral: {
1543 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001544 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001545 return TemplateArgumentLoc(TemplateArgument(E), E);
1546 }
1547
1548 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001549 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1550
1551 case TemplateArgument::TemplateExpansion:
1552 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1553
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001554 case TemplateArgument::Expression:
1555 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1556
1557 case TemplateArgument::Pack:
1558 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1559 }
1560
1561 return TemplateArgumentLoc();
1562}
1563
1564
1565/// \brief Convert the given deduced template argument and add it to the set of
1566/// fully-converted template arguments.
1567static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1568 DeducedTemplateArgument Arg,
1569 NamedDecl *Template,
1570 QualType NTTPType,
1571 TemplateDeductionInfo &Info,
1572 bool InFunctionTemplate,
1573 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1574 if (Arg.getKind() == TemplateArgument::Pack) {
1575 // This is a template argument pack, so check each of its arguments against
1576 // the template parameter.
1577 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1578 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001579 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001580 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001581 // When converting the deduced template argument, append it to the
1582 // general output list. We need to do this so that the template argument
1583 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001584 DeducedTemplateArgument InnerArg(*PA);
1585 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1586 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1587 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001588 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001589 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001590
1591 // Move the converted template argument into our argument pack.
1592 PackedArgsBuilder.push_back(Output.back());
1593 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001594 }
1595
1596 // Create the resulting argument pack.
1597 TemplateArgument *PackedArgs = 0;
1598 if (!PackedArgsBuilder.empty()) {
1599 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1600 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1601 }
1602 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1603 return false;
1604 }
1605
1606 // Convert the deduced template argument into a template
1607 // argument that we can check, almost as if the user had written
1608 // the template argument explicitly.
1609 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1610 Info.getLocation());
1611
1612 // Check the template argument, converting it as necessary.
1613 return S.CheckTemplateArgument(Param, ArgLoc,
1614 Template,
1615 Template->getLocation(),
1616 Template->getSourceRange().getEnd(),
1617 Output,
1618 InFunctionTemplate
1619 ? (Arg.wasDeducedFromArrayBound()
1620 ? Sema::CTAK_DeducedFromArrayBound
1621 : Sema::CTAK_Deduced)
1622 : Sema::CTAK_Specified);
1623}
1624
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001625/// Complete template argument deduction for a class template partial
1626/// specialization.
1627static Sema::TemplateDeductionResult
1628FinishTemplateArgumentDeduction(Sema &S,
1629 ClassTemplatePartialSpecializationDecl *Partial,
1630 const TemplateArgumentList &TemplateArgs,
1631 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001632 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001633 // Trap errors.
1634 Sema::SFINAETrap Trap(S);
1635
1636 Sema::ContextRAII SavedContext(S, Partial);
1637
1638 // C++ [temp.deduct.type]p2:
1639 // [...] or if any template argument remains neither deduced nor
1640 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001641 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001642 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1643 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001644 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001645 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001646 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001647 return Sema::TDK_Incomplete;
1648 }
1649
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001650 // We have deduced this argument, so it still needs to be
1651 // checked and converted.
1652
1653 // First, for a non-type template parameter type that is
1654 // initialized by a declaration, we need the type of the
1655 // corresponding non-type template parameter.
1656 QualType NTTPType;
1657 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001658 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001659 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001660 if (NTTPType->isDependentType()) {
1661 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1662 Builder.data(), Builder.size());
1663 NTTPType = S.SubstType(NTTPType,
1664 MultiLevelTemplateArgumentList(TemplateArgs),
1665 NTTP->getLocation(),
1666 NTTP->getDeclName());
1667 if (NTTPType.isNull()) {
1668 Info.Param = makeTemplateParameter(Param);
1669 // FIXME: These template arguments are temporary. Free them!
1670 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1671 Builder.data(),
1672 Builder.size()));
1673 return Sema::TDK_SubstitutionFailure;
1674 }
1675 }
1676 }
1677
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001678 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1679 Partial, NTTPType, Info, false,
1680 Builder)) {
1681 Info.Param = makeTemplateParameter(Param);
1682 // FIXME: These template arguments are temporary. Free them!
1683 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1684 Builder.size()));
1685 return Sema::TDK_SubstitutionFailure;
1686 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001687 }
1688
1689 // Form the template argument list from the deduced template arguments.
1690 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001691 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1692 Builder.size());
1693
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001694 Info.reset(DeducedArgumentList);
1695
1696 // Substitute the deduced template arguments into the template
1697 // arguments of the class template partial specialization, and
1698 // verify that the instantiated template arguments are both valid
1699 // and are equivalent to the template arguments originally provided
1700 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001701 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001702 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1703 const TemplateArgumentLoc *PartialTemplateArgs
1704 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001705
1706 // Note that we don't provide the langle and rangle locations.
1707 TemplateArgumentListInfo InstArgs;
1708
Douglas Gregore02e2622010-12-22 21:19:48 +00001709 if (S.Subst(PartialTemplateArgs,
1710 Partial->getNumTemplateArgsAsWritten(),
1711 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1712 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1713 if (ParamIdx >= Partial->getTemplateParameters()->size())
1714 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1715
1716 Decl *Param
1717 = const_cast<NamedDecl *>(
1718 Partial->getTemplateParameters()->getParam(ParamIdx));
1719 Info.Param = makeTemplateParameter(Param);
1720 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1721 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001722 }
1723
Douglas Gregor910f8002010-11-07 23:05:16 +00001724 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001725 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001726 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001727 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001728
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001729 TemplateParameterList *TemplateParams
1730 = ClassTemplate->getTemplateParameters();
1731 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001732 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001733 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001734 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001735 Info.FirstArg = TemplateArgs[I];
1736 Info.SecondArg = InstArg;
1737 return Sema::TDK_NonDeducedMismatch;
1738 }
1739 }
1740
1741 if (Trap.hasErrorOccurred())
1742 return Sema::TDK_SubstitutionFailure;
1743
1744 return Sema::TDK_Success;
1745}
1746
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001747/// \brief Perform template argument deduction to determine whether
1748/// the given template arguments match the given class template
1749/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001750Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001751Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001752 const TemplateArgumentList &TemplateArgs,
1753 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001754 // C++ [temp.class.spec.match]p2:
1755 // A partial specialization matches a given actual template
1756 // argument list if the template arguments of the partial
1757 // specialization can be deduced from the actual template argument
1758 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001759 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001760 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001761 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001762 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001763 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001764 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001765 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001766 TemplateArgs, Info, Deduced))
1767 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001768
Douglas Gregor637a4092009-06-10 23:47:09 +00001769 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001770 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001771 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001772 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001773
Douglas Gregorbb260412009-06-14 08:02:22 +00001774 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001775 return Sema::TDK_SubstitutionFailure;
1776
1777 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1778 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001779}
Douglas Gregor031a5882009-06-13 00:26:55 +00001780
Douglas Gregor41128772009-06-26 23:27:24 +00001781/// \brief Determine whether the given type T is a simple-template-id type.
1782static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001783 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001784 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001785 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor41128772009-06-26 23:27:24 +00001787 return false;
1788}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001789
1790/// \brief Substitute the explicitly-provided template arguments into the
1791/// given function template according to C++ [temp.arg.explicit].
1792///
1793/// \param FunctionTemplate the function template into which the explicit
1794/// template arguments will be substituted.
1795///
Mike Stump1eb44332009-09-09 15:08:12 +00001796/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001797/// arguments.
1798///
Mike Stump1eb44332009-09-09 15:08:12 +00001799/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001800/// with the converted and checked explicit template arguments.
1801///
Mike Stump1eb44332009-09-09 15:08:12 +00001802/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001803/// parameters.
1804///
1805/// \param FunctionType if non-NULL, the result type of the function template
1806/// will also be instantiated and the pointed-to value will be updated with
1807/// the instantiated function type.
1808///
1809/// \param Info if substitution fails for any reason, this object will be
1810/// populated with more information about the failure.
1811///
1812/// \returns TDK_Success if substitution was successful, or some failure
1813/// condition.
1814Sema::TemplateDeductionResult
1815Sema::SubstituteExplicitTemplateArguments(
1816 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001817 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001818 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001819 llvm::SmallVectorImpl<QualType> &ParamTypes,
1820 QualType *FunctionType,
1821 TemplateDeductionInfo &Info) {
1822 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1823 TemplateParameterList *TemplateParams
1824 = FunctionTemplate->getTemplateParameters();
1825
John McCalld5532b62009-11-23 01:53:49 +00001826 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001827 // No arguments to substitute; just copy over the parameter types and
1828 // fill in the function type.
1829 for (FunctionDecl::param_iterator P = Function->param_begin(),
1830 PEnd = Function->param_end();
1831 P != PEnd;
1832 ++P)
1833 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor83314aa2009-07-08 20:55:45 +00001835 if (FunctionType)
1836 *FunctionType = Function->getType();
1837 return TDK_Success;
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregor83314aa2009-07-08 20:55:45 +00001840 // Substitution of the explicit template arguments into a function template
1841 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001842 SFINAETrap Trap(*this);
1843
Douglas Gregor83314aa2009-07-08 20:55:45 +00001844 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001845 // Template arguments that are present shall be specified in the
1846 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001847 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001848 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001849 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001850
1851 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001852 // explicitly-specified template arguments against this function template,
1853 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001854 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001855 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001856 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1857 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001858 if (Inst)
1859 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor83314aa2009-07-08 20:55:45 +00001861 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001862 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001863 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001864 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001865 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001866 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001867 if (Index >= TemplateParams->size())
1868 Index = TemplateParams->size() - 1;
1869 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001870 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Douglas Gregor83314aa2009-07-08 20:55:45 +00001873 // Form the template argument list from the explicitly-specified
1874 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001876 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001877 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001878
John McCalldf41f182010-10-12 19:40:14 +00001879 // Template argument deduction and the final substitution should be
1880 // done in the context of the templated declaration. Explicit
1881 // argument substitution, on the other hand, needs to happen in the
1882 // calling context.
1883 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1884
Douglas Gregor83314aa2009-07-08 20:55:45 +00001885 // Instantiate the types of each of the function parameters given the
1886 // explicitly-specified template arguments.
1887 for (FunctionDecl::param_iterator P = Function->param_begin(),
1888 PEnd = Function->param_end();
1889 P != PEnd;
1890 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001891 QualType ParamType
1892 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001893 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1894 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001895 if (ParamType.isNull() || Trap.hasErrorOccurred())
1896 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Douglas Gregor83314aa2009-07-08 20:55:45 +00001898 ParamTypes.push_back(ParamType);
1899 }
1900
1901 // If the caller wants a full function type back, instantiate the return
1902 // type and form that function type.
1903 if (FunctionType) {
1904 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001905 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001906 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001907 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
1909 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001910 = SubstType(Proto->getResultType(),
1911 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1912 Function->getTypeSpecStartLoc(),
1913 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001914 if (ResultType.isNull() || Trap.hasErrorOccurred())
1915 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
1917 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001918 ParamTypes.data(), ParamTypes.size(),
1919 Proto->isVariadic(),
1920 Proto->getTypeQuals(),
1921 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001922 Function->getDeclName(),
1923 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001924 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1925 return TDK_SubstitutionFailure;
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor83314aa2009-07-08 20:55:45 +00001928 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001929 // Trailing template arguments that can be deduced (14.8.2) may be
1930 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001931 // template arguments can be deduced, they may all be omitted; in this
1932 // case, the empty template argument list <> itself may also be omitted.
1933 //
1934 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001935 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936 Deduced.reserve(TemplateParams->size());
1937 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001938 Deduced.push_back(ExplicitArgumentList->get(I));
1939
Douglas Gregor83314aa2009-07-08 20:55:45 +00001940 return TDK_Success;
1941}
1942
Mike Stump1eb44332009-09-09 15:08:12 +00001943/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001944/// checking the deduced template arguments for completeness and forming
1945/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001946Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001947Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001948 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1949 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001950 FunctionDecl *&Specialization,
1951 TemplateDeductionInfo &Info) {
1952 TemplateParameterList *TemplateParams
1953 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Douglas Gregor83314aa2009-07-08 20:55:45 +00001955 // Template argument deduction for function templates in a SFINAE context.
1956 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001957 SFINAETrap Trap(*this);
1958
Douglas Gregor83314aa2009-07-08 20:55:45 +00001959 // Enter a new template instantiation context while we instantiate the
1960 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001962 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001963 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1964 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001965 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001966 return TDK_InstantiationDepth;
1967
John McCall96db3102010-04-29 01:18:58 +00001968 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001969
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001970 // C++ [temp.deduct.type]p2:
1971 // [...] or if any template argument remains neither deduced nor
1972 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001973 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001974 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1975 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001976
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001977 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001978 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001979 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001980 // argument, because it was explicitly-specified. Just record the
1981 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001982 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001983 continue;
1984 }
1985
1986 // We have deduced this argument, so it still needs to be
1987 // checked and converted.
1988
1989 // First, for a non-type template parameter type that is
1990 // initialized by a declaration, we need the type of the
1991 // corresponding non-type template parameter.
1992 QualType NTTPType;
1993 if (NonTypeTemplateParmDecl *NTTP
1994 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001995 NTTPType = NTTP->getType();
1996 if (NTTPType->isDependentType()) {
1997 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1998 Builder.data(), Builder.size());
1999 NTTPType = SubstType(NTTPType,
2000 MultiLevelTemplateArgumentList(TemplateArgs),
2001 NTTP->getLocation(),
2002 NTTP->getDeclName());
2003 if (NTTPType.isNull()) {
2004 Info.Param = makeTemplateParameter(Param);
2005 // FIXME: These template arguments are temporary. Free them!
2006 Info.reset(TemplateArgumentList::CreateCopy(Context,
2007 Builder.data(),
2008 Builder.size()));
2009 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002010 }
2011 }
2012 }
2013
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002014 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2015 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002016 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002017 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002018 // FIXME: These template arguments are temporary. Free them!
2019 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002020 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002021 return TDK_SubstitutionFailure;
2022 }
2023
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002024 continue;
2025 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002026
2027 // C++0x [temp.arg.explicit]p3:
2028 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2029 // be deduced to an empty sequence of template arguments.
2030 // FIXME: Where did the word "trailing" come from?
2031 if (Param->isTemplateParameterPack()) {
2032 Builder.push_back(TemplateArgument(0, 0));
2033 continue;
2034 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002035
2036 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002037 TemplateArgumentLoc DefArg
2038 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2039 FunctionTemplate->getLocation(),
2040 FunctionTemplate->getSourceRange().getEnd(),
2041 Param,
2042 Builder);
2043
2044 // If there was no default argument, deduction is incomplete.
2045 if (DefArg.getArgument().isNull()) {
2046 Info.Param = makeTemplateParameter(
2047 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2048 return TDK_Incomplete;
2049 }
2050
2051 // Check whether we can actually use the default argument.
2052 if (CheckTemplateArgument(Param, DefArg,
2053 FunctionTemplate,
2054 FunctionTemplate->getLocation(),
2055 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002056 Builder,
2057 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002058 Info.Param = makeTemplateParameter(
2059 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002060 // FIXME: These template arguments are temporary. Free them!
2061 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2062 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002063 return TDK_SubstitutionFailure;
2064 }
2065
2066 // If we get here, we successfully used the default template argument.
2067 }
2068
2069 // Form the template argument list from the deduced template arguments.
2070 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002071 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002072 Info.reset(DeducedArgumentList);
2073
Mike Stump1eb44332009-09-09 15:08:12 +00002074 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002075 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002076 DeclContext *Owner = FunctionTemplate->getDeclContext();
2077 if (FunctionTemplate->getFriendObjectKind())
2078 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002079 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002080 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002081 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002082 if (!Specialization)
2083 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregorf8825742009-09-15 18:26:13 +00002085 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2086 FunctionTemplate->getCanonicalDecl());
2087
Mike Stump1eb44332009-09-09 15:08:12 +00002088 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002089 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002090 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2091 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002092 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregor83314aa2009-07-08 20:55:45 +00002094 // There may have been an error that did not prevent us from constructing a
2095 // declaration. Mark the declaration invalid and return with a substitution
2096 // failure.
2097 if (Trap.hasErrorOccurred()) {
2098 Specialization->setInvalidDecl(true);
2099 return TDK_SubstitutionFailure;
2100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregor9b623632010-10-12 23:32:35 +00002102 // If we suppressed any diagnostics while performing template argument
2103 // deduction, and if we haven't already instantiated this declaration,
2104 // keep track of these diagnostics. They'll be emitted if this specialization
2105 // is actually used.
2106 if (Info.diag_begin() != Info.diag_end()) {
2107 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2108 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2109 if (Pos == SuppressedDiagnostics.end())
2110 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2111 .append(Info.diag_begin(), Info.diag_end());
2112 }
2113
Mike Stump1eb44332009-09-09 15:08:12 +00002114 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002115}
2116
John McCall9c72c602010-08-27 09:08:28 +00002117/// Gets the type of a function for template-argument-deducton
2118/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002119static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002120 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002121 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002122 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002123 if (Method->isInstance()) {
2124 // An instance method that's referenced in a form that doesn't
2125 // look like a member pointer is just invalid.
2126 if (!R.HasFormOfMemberPointer) return QualType();
2127
John McCalleff92132010-02-02 02:21:27 +00002128 return Context.getMemberPointerType(Fn->getType(),
2129 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002130 }
2131
2132 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002133 return Context.getPointerType(Fn->getType());
2134}
2135
2136/// Apply the deduction rules for overload sets.
2137///
2138/// \return the null type if this argument should be treated as an
2139/// undeduced context
2140static QualType
2141ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002142 Expr *Arg, QualType ParamType,
2143 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002144
2145 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002146
John McCall9c72c602010-08-27 09:08:28 +00002147 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002148
Douglas Gregor75f21af2010-08-30 21:04:23 +00002149 // C++0x [temp.deduct.call]p4
2150 unsigned TDF = 0;
2151 if (ParamWasReference)
2152 TDF |= TDF_ParamWithReferenceType;
2153 if (R.IsAddressOfOperand)
2154 TDF |= TDF_IgnoreQualifiers;
2155
John McCalleff92132010-02-02 02:21:27 +00002156 // If there were explicit template arguments, we can only find
2157 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2158 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002159 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002160 // But we can still look for an explicit specialization.
2161 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002162 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002163 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002164 return QualType();
2165 }
2166
2167 // C++0x [temp.deduct.call]p6:
2168 // When P is a function type, pointer to function type, or pointer
2169 // to member function type:
2170
2171 if (!ParamType->isFunctionType() &&
2172 !ParamType->isFunctionPointerType() &&
2173 !ParamType->isMemberFunctionPointerType())
2174 return QualType();
2175
2176 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002177 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2178 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002179 NamedDecl *D = (*I)->getUnderlyingDecl();
2180
2181 // - If the argument is an overload set containing one or more
2182 // function templates, the parameter is treated as a
2183 // non-deduced context.
2184 if (isa<FunctionTemplateDecl>(D))
2185 return QualType();
2186
2187 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002188 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2189 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002190
Douglas Gregor75f21af2010-08-30 21:04:23 +00002191 // Function-to-pointer conversion.
2192 if (!ParamWasReference && ParamType->isPointerType() &&
2193 ArgType->isFunctionType())
2194 ArgType = S.Context.getPointerType(ArgType);
2195
John McCalleff92132010-02-02 02:21:27 +00002196 // - If the argument is an overload set (not containing function
2197 // templates), trial argument deduction is attempted using each
2198 // of the members of the set. If deduction succeeds for only one
2199 // of the overload set members, that member is used as the
2200 // argument value for the deduction. If deduction succeeds for
2201 // more than one member of the overload set the parameter is
2202 // treated as a non-deduced context.
2203
2204 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2205 // Type deduction is done independently for each P/A pair, and
2206 // the deduced template argument values are then combined.
2207 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002208 llvm::SmallVector<DeducedTemplateArgument, 8>
2209 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002210 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002211 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002212 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002213 ParamType, ArgType,
2214 Info, Deduced, TDF);
2215 if (Result) continue;
2216 if (!Match.isNull()) return QualType();
2217 Match = ArgType;
2218 }
2219
2220 return Match;
2221}
2222
Douglas Gregore53060f2009-06-25 22:08:12 +00002223/// \brief Perform template argument deduction from a function call
2224/// (C++ [temp.deduct.call]).
2225///
2226/// \param FunctionTemplate the function template for which we are performing
2227/// template argument deduction.
2228///
Douglas Gregor48026d22010-01-11 18:40:55 +00002229/// \param ExplicitTemplateArguments the explicit template arguments provided
2230/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002231///
Douglas Gregore53060f2009-06-25 22:08:12 +00002232/// \param Args the function call arguments
2233///
2234/// \param NumArgs the number of arguments in Args
2235///
Douglas Gregor48026d22010-01-11 18:40:55 +00002236/// \param Name the name of the function being called. This is only significant
2237/// when the function template is a conversion function template, in which
2238/// case this routine will also perform template argument deduction based on
2239/// the function to which
2240///
Douglas Gregore53060f2009-06-25 22:08:12 +00002241/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002242/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002243/// template argument deduction.
2244///
2245/// \param Info the argument will be updated to provide additional information
2246/// about template argument deduction.
2247///
2248/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002249Sema::TemplateDeductionResult
2250Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002251 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002252 Expr **Args, unsigned NumArgs,
2253 FunctionDecl *&Specialization,
2254 TemplateDeductionInfo &Info) {
2255 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002256
Douglas Gregore53060f2009-06-25 22:08:12 +00002257 // C++ [temp.deduct.call]p1:
2258 // Template argument deduction is done by comparing each function template
2259 // parameter type (call it P) with the type of the corresponding argument
2260 // of the call (call it A) as described below.
2261 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002262 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002263 return TDK_TooFewArguments;
2264 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002265 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002266 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00002267 if (!Proto->isVariadic())
2268 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Douglas Gregore53060f2009-06-25 22:08:12 +00002270 CheckArgs = Function->getNumParams();
2271 }
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002273 // The types of the parameters from which we will perform template argument
2274 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002275 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002276 TemplateParameterList *TemplateParams
2277 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002278 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002279 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002280 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002281 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002282 TemplateDeductionResult Result =
2283 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002284 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002285 Deduced,
2286 ParamTypes,
2287 0,
2288 Info);
2289 if (Result)
2290 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002291
2292 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002293 } else {
2294 // Just fill in the parameter types from the function declaration.
2295 for (unsigned I = 0; I != CheckArgs; ++I)
2296 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2297 }
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002299 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002300 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002301 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002302 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002303 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregor75f21af2010-08-30 21:04:23 +00002305 // C++0x [temp.deduct.call]p3:
2306 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2307 // are ignored for type deduction.
2308 if (ParamType.getCVRQualifiers())
2309 ParamType = ParamType.getLocalUnqualifiedType();
2310 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2311 if (ParamRefType) {
2312 // [...] If P is a reference type, the type referred to by P is used
2313 // for type deduction.
2314 ParamType = ParamRefType->getPointeeType();
2315 }
2316
John McCalleff92132010-02-02 02:21:27 +00002317 // Overload sets usually make this parameter an undeduced
2318 // context, but there are sometimes special circumstances.
2319 if (ArgType == Context.OverloadTy) {
2320 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002321 Args[I], ParamType,
2322 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002323 if (ArgType.isNull())
2324 continue;
2325 }
2326
Douglas Gregor75f21af2010-08-30 21:04:23 +00002327 if (ParamRefType) {
2328 // C++0x [temp.deduct.call]p3:
2329 // [...] If P is of the form T&&, where T is a template parameter, and
2330 // the argument is an lvalue, the type A& is used in place of A for
2331 // type deduction.
2332 if (ParamRefType->isRValueReferenceType() &&
2333 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002334 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002335 ArgType = Context.getLValueReferenceType(ArgType);
2336 } else {
2337 // C++ [temp.deduct.call]p2:
2338 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002339 // - If A is an array type, the pointer type produced by the
2340 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002341 // A for type deduction; otherwise,
2342 if (ArgType->isArrayType())
2343 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002344 // - If A is a function type, the pointer type produced by the
2345 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002346 // of A for type deduction; otherwise,
2347 else if (ArgType->isFunctionType())
2348 ArgType = Context.getPointerType(ArgType);
2349 else {
2350 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2351 // type are ignored for type deduction.
2352 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002353 if (ArgType.getCVRQualifiers())
2354 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002355 }
2356 }
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregore53060f2009-06-25 22:08:12 +00002358 // C++0x [temp.deduct.call]p4:
2359 // In general, the deduction process attempts to find template argument
2360 // values that will make the deduced A identical to A (after the type A
2361 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002362 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor508f1c82009-06-26 23:10:12 +00002364 // - If the original P is a reference type, the deduced A (i.e., the
2365 // type referred to by the reference) can be more cv-qualified than
2366 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002367 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002368 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002369 // - The transformed A can be another pointer or pointer to member
2370 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002371 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002372 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2373 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002374 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002375 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002376 // transformed A can be a derived class of the deduced A. Likewise,
2377 // if P is a pointer to a class of the form simple-template-id, the
2378 // transformed A can be a pointer to a derived class pointed to by
2379 // the deduced A.
2380 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002381 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002382 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002383 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002384 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Douglas Gregore53060f2009-06-25 22:08:12 +00002386 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002387 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002388 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002389 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002390 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002392 // FIXME: we need to check that the deduced A is the same as A,
2393 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002394 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002395
Mike Stump1eb44332009-09-09 15:08:12 +00002396 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002397 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002398 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002399}
2400
Douglas Gregor83314aa2009-07-08 20:55:45 +00002401/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002402/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2403/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002404///
2405/// \param FunctionTemplate the function template for which we are performing
2406/// template argument deduction.
2407///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002408/// \param ExplicitTemplateArguments the explicitly-specified template
2409/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002410///
2411/// \param ArgFunctionType the function type that will be used as the
2412/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002413/// function template's function type. This type may be NULL, if there is no
2414/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002415///
2416/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002417/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002418/// template argument deduction.
2419///
2420/// \param Info the argument will be updated to provide additional information
2421/// about template argument deduction.
2422///
2423/// \returns the result of template argument deduction.
2424Sema::TemplateDeductionResult
2425Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002426 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002427 QualType ArgFunctionType,
2428 FunctionDecl *&Specialization,
2429 TemplateDeductionInfo &Info) {
2430 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2431 TemplateParameterList *TemplateParams
2432 = FunctionTemplate->getTemplateParameters();
2433 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Douglas Gregor83314aa2009-07-08 20:55:45 +00002435 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002436 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002437 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2438 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002439 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002440 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002441 if (TemplateDeductionResult Result
2442 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002443 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002444 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002445 &FunctionType, Info))
2446 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002447
2448 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002449 }
2450
2451 // Template argument deduction for function templates in a SFINAE context.
2452 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002453 SFINAETrap Trap(*this);
2454
John McCalleff92132010-02-02 02:21:27 +00002455 Deduced.resize(TemplateParams->size());
2456
Douglas Gregor4b52e252009-12-21 23:17:24 +00002457 if (!ArgFunctionType.isNull()) {
2458 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002459 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002460 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002461 FunctionType, ArgFunctionType, Info,
2462 Deduced, 0))
2463 return Result;
2464 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002465
2466 if (TemplateDeductionResult Result
2467 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2468 NumExplicitlySpecified,
2469 Specialization, Info))
2470 return Result;
2471
2472 // If the requested function type does not match the actual type of the
2473 // specialization, template argument deduction fails.
2474 if (!ArgFunctionType.isNull() &&
2475 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2476 return TDK_NonDeducedMismatch;
2477
2478 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002479}
2480
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002481/// \brief Deduce template arguments for a templated conversion
2482/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2483/// conversion function template specialization.
2484Sema::TemplateDeductionResult
2485Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2486 QualType ToType,
2487 CXXConversionDecl *&Specialization,
2488 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002489 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002490 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2491 QualType FromType = Conv->getConversionType();
2492
2493 // Canonicalize the types for deduction.
2494 QualType P = Context.getCanonicalType(FromType);
2495 QualType A = Context.getCanonicalType(ToType);
2496
2497 // C++0x [temp.deduct.conv]p3:
2498 // If P is a reference type, the type referred to by P is used for
2499 // type deduction.
2500 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2501 P = PRef->getPointeeType();
2502
2503 // C++0x [temp.deduct.conv]p3:
2504 // If A is a reference type, the type referred to by A is used
2505 // for type deduction.
2506 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2507 A = ARef->getPointeeType();
2508 // C++ [temp.deduct.conv]p2:
2509 //
Mike Stump1eb44332009-09-09 15:08:12 +00002510 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002511 else {
2512 assert(!A->isReferenceType() && "Reference types were handled above");
2513
2514 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002515 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002516 // of P for type deduction; otherwise,
2517 if (P->isArrayType())
2518 P = Context.getArrayDecayedType(P);
2519 // - If P is a function type, the pointer type produced by the
2520 // function-to-pointer standard conversion (4.3) is used in
2521 // place of P for type deduction; otherwise,
2522 else if (P->isFunctionType())
2523 P = Context.getPointerType(P);
2524 // - If P is a cv-qualified type, the top level cv-qualifiers of
2525 // P’s type are ignored for type deduction.
2526 else
2527 P = P.getUnqualifiedType();
2528
2529 // C++0x [temp.deduct.conv]p3:
2530 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2531 // type are ignored for type deduction.
2532 A = A.getUnqualifiedType();
2533 }
2534
2535 // Template argument deduction for function templates in a SFINAE context.
2536 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002537 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002538
2539 // C++ [temp.deduct.conv]p1:
2540 // Template argument deduction is done by comparing the return
2541 // type of the template conversion function (call it P) with the
2542 // type that is required as the result of the conversion (call it
2543 // A) as described in 14.8.2.4.
2544 TemplateParameterList *TemplateParams
2545 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002546 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002547 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002548
2549 // C++0x [temp.deduct.conv]p4:
2550 // In general, the deduction process attempts to find template
2551 // argument values that will make the deduced A identical to
2552 // A. However, there are two cases that allow a difference:
2553 unsigned TDF = 0;
2554 // - If the original A is a reference type, A can be more
2555 // cv-qualified than the deduced A (i.e., the type referred to
2556 // by the reference)
2557 if (ToType->isReferenceType())
2558 TDF |= TDF_ParamWithReferenceType;
2559 // - The deduced A can be another pointer or pointer to member
2560 // type that can be converted to A via a qualification
2561 // conversion.
2562 //
2563 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2564 // both P and A are pointers or member pointers. In this case, we
2565 // just ignore cv-qualifiers completely).
2566 if ((P->isPointerType() && A->isPointerType()) ||
2567 (P->isMemberPointerType() && P->isMemberPointerType()))
2568 TDF |= TDF_IgnoreQualifiers;
2569 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002570 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002571 P, A, Info, Deduced, TDF))
2572 return Result;
2573
2574 // FIXME: we need to check that the deduced A is the same as A,
2575 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002577 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002578 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002579 FunctionDecl *Spec = 0;
2580 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002581 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2582 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002583 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2584 return Result;
2585}
2586
Douglas Gregor4b52e252009-12-21 23:17:24 +00002587/// \brief Deduce template arguments for a function template when there is
2588/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2589///
2590/// \param FunctionTemplate the function template for which we are performing
2591/// template argument deduction.
2592///
2593/// \param ExplicitTemplateArguments the explicitly-specified template
2594/// arguments.
2595///
2596/// \param Specialization if template argument deduction was successful,
2597/// this will be set to the function template specialization produced by
2598/// template argument deduction.
2599///
2600/// \param Info the argument will be updated to provide additional information
2601/// about template argument deduction.
2602///
2603/// \returns the result of template argument deduction.
2604Sema::TemplateDeductionResult
2605Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2606 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2607 FunctionDecl *&Specialization,
2608 TemplateDeductionInfo &Info) {
2609 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2610 QualType(), Specialization, Info);
2611}
2612
Douglas Gregor8a514912009-09-14 18:39:43 +00002613/// \brief Stores the result of comparing the qualifiers of two types.
2614enum DeductionQualifierComparison {
2615 NeitherMoreQualified = 0,
2616 ParamMoreQualified,
2617 ArgMoreQualified
2618};
2619
2620/// \brief Deduce the template arguments during partial ordering by comparing
2621/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2622///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002623/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002624///
2625/// \param TemplateParams the template parameters that we are deducing
2626///
2627/// \param ParamIn the parameter type
2628///
2629/// \param ArgIn the argument type
2630///
2631/// \param Info information about the template argument deduction itself
2632///
2633/// \param Deduced the deduced template arguments
2634///
2635/// \returns the result of template argument deduction so far. Note that a
2636/// "success" result means that template argument deduction has not yet failed,
2637/// but it may still fail, later, for other reasons.
2638static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002639DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002640 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002641 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002642 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002643 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2644 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002645 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2646 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002647
2648 // C++0x [temp.deduct.partial]p5:
2649 // Before the partial ordering is done, certain transformations are
2650 // performed on the types used for partial ordering:
2651 // - If P is a reference type, P is replaced by the type referred to.
2652 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002653 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002654 Param = ParamRef->getPointeeType();
2655
2656 // - If A is a reference type, A is replaced by the type referred to.
2657 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002658 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002659 Arg = ArgRef->getPointeeType();
2660
John McCalle27ec8a2009-10-23 23:03:21 +00002661 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002662 // C++0x [temp.deduct.partial]p6:
2663 // If both P and A were reference types (before being replaced with the
2664 // type referred to above), determine which of the two types (if any) is
2665 // more cv-qualified than the other; otherwise the types are considered to
2666 // be equally cv-qualified for partial ordering purposes. The result of this
2667 // determination will be used below.
2668 //
2669 // We save this information for later, using it only when deduction
2670 // succeeds in both directions.
2671 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2672 if (Param.isMoreQualifiedThan(Arg))
2673 QualifierResult = ParamMoreQualified;
2674 else if (Arg.isMoreQualifiedThan(Param))
2675 QualifierResult = ArgMoreQualified;
2676 QualifierComparisons->push_back(QualifierResult);
2677 }
2678
2679 // C++0x [temp.deduct.partial]p7:
2680 // Remove any top-level cv-qualifiers:
2681 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2682 // version of P.
2683 Param = Param.getUnqualifiedType();
2684 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2685 // version of A.
2686 Arg = Arg.getUnqualifiedType();
2687
2688 // C++0x [temp.deduct.partial]p8:
2689 // Using the resulting types P and A the deduction is then done as
2690 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2691 // from the argument template is considered to be at least as specialized
2692 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002693 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002694 Deduced, TDF_None);
2695}
2696
2697static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002698MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2699 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002700 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002701 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002702
2703/// \brief If this is a non-static member function,
2704static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2705 CXXMethodDecl *Method,
2706 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2707 if (Method->isStatic())
2708 return;
2709
2710 // C++ [over.match.funcs]p4:
2711 //
2712 // For non-static member functions, the type of the implicit
2713 // object parameter is
2714 // — "lvalue reference to cv X" for functions declared without a
2715 // ref-qualifier or with the & ref-qualifier
2716 // - "rvalue reference to cv X" for functions declared with the
2717 // && ref-qualifier
2718 //
2719 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2720 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2721 ArgTy = Context.getQualifiedType(ArgTy,
2722 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2723 ArgTy = Context.getLValueReferenceType(ArgTy);
2724 ArgTypes.push_back(ArgTy);
2725}
2726
Douglas Gregor8a514912009-09-14 18:39:43 +00002727/// \brief Determine whether the function template \p FT1 is at least as
2728/// specialized as \p FT2.
2729static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002730 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002731 FunctionTemplateDecl *FT1,
2732 FunctionTemplateDecl *FT2,
2733 TemplatePartialOrderingContext TPOC,
2734 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2735 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2736 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2737 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2738 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2739
2740 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2741 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002742 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002743 Deduced.resize(TemplateParams->size());
2744
2745 // C++0x [temp.deduct.partial]p3:
2746 // The types used to determine the ordering depend on the context in which
2747 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002748 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002749 CXXMethodDecl *Method1 = 0;
2750 CXXMethodDecl *Method2 = 0;
2751 bool IsNonStatic2 = false;
2752 bool IsNonStatic1 = false;
2753 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002754 switch (TPOC) {
2755 case TPOC_Call: {
2756 // - In the context of a function call, the function parameter types are
2757 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002758 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2759 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2760 IsNonStatic1 = Method1 && !Method1->isStatic();
2761 IsNonStatic2 = Method2 && !Method2->isStatic();
2762
2763 // C++0x [temp.func.order]p3:
2764 // [...] If only one of the function templates is a non-static
2765 // member, that function template is considered to have a new
2766 // first parameter inserted in its function parameter list. The
2767 // new parameter is of type "reference to cv A," where cv are
2768 // the cv-qualifiers of the function template (if any) and A is
2769 // the class of which the function template is a member.
2770 //
2771 // C++98/03 doesn't have this provision, so instead we drop the
2772 // first argument of the free function or static member, which
2773 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002774 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002775 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2776 IsNonStatic2 && !IsNonStatic1;
2777 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002778 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2779 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002780 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002781
2782 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002783 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2784 IsNonStatic1 && !IsNonStatic2;
2785 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002786 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2787 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002788 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002789
2790 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002791 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002792 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002793 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002794 Args2[I],
2795 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002796 Info,
2797 Deduced,
2798 QualifierComparisons))
2799 return false;
2800
2801 break;
2802 }
2803
2804 case TPOC_Conversion:
2805 // - In the context of a call to a conversion operator, the return types
2806 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002807 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002808 TemplateParams,
2809 Proto2->getResultType(),
2810 Proto1->getResultType(),
2811 Info,
2812 Deduced,
2813 QualifierComparisons))
2814 return false;
2815 break;
2816
2817 case TPOC_Other:
2818 // - In other contexts (14.6.6.2) the function template’s function type
2819 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002820 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002821 TemplateParams,
2822 FD2->getType(),
2823 FD1->getType(),
2824 Info,
2825 Deduced,
2826 QualifierComparisons))
2827 return false;
2828 break;
2829 }
2830
2831 // C++0x [temp.deduct.partial]p11:
2832 // In most cases, all template parameters must have values in order for
2833 // deduction to succeed, but for partial ordering purposes a template
2834 // parameter may remain without a value provided it is not used in the
2835 // types being used for partial ordering. [ Note: a template parameter used
2836 // in a non-deduced context is considered used. -end note]
2837 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2838 for (; ArgIdx != NumArgs; ++ArgIdx)
2839 if (Deduced[ArgIdx].isNull())
2840 break;
2841
2842 if (ArgIdx == NumArgs) {
2843 // All template arguments were deduced. FT1 is at least as specialized
2844 // as FT2.
2845 return true;
2846 }
2847
Douglas Gregore73bb602009-09-14 21:25:05 +00002848 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002849 llvm::SmallVector<bool, 4> UsedParameters;
2850 UsedParameters.resize(TemplateParams->size());
2851 switch (TPOC) {
2852 case TPOC_Call: {
2853 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002854 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2855 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2856 TemplateParams->getDepth(), UsedParameters);
2857 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002858 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2859 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002860 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002861 break;
2862 }
2863
2864 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002865 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2866 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002867 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002868 break;
2869
2870 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002871 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2872 TemplateParams->getDepth(),
2873 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002874 break;
2875 }
2876
2877 for (; ArgIdx != NumArgs; ++ArgIdx)
2878 // If this argument had no value deduced but was used in one of the types
2879 // used for partial ordering, then deduction fails.
2880 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2881 return false;
2882
2883 return true;
2884}
2885
2886
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002887/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002888/// to the rules of function template partial ordering (C++ [temp.func.order]).
2889///
2890/// \param FT1 the first function template
2891///
2892/// \param FT2 the second function template
2893///
Douglas Gregor8a514912009-09-14 18:39:43 +00002894/// \param TPOC the context in which we are performing partial ordering of
2895/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002896///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002897/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002898/// template is more specialized, returns NULL.
2899FunctionTemplateDecl *
2900Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2901 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002902 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002903 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002904 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002905 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2906 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002907 &QualifierComparisons);
2908
2909 if (Better1 != Better2) // We have a clear winner
2910 return Better1? FT1 : FT2;
2911
2912 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002913 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002914
2915
2916 // C++0x [temp.deduct.partial]p10:
2917 // If for each type being considered a given template is at least as
2918 // specialized for all types and more specialized for some set of types and
2919 // the other template is not more specialized for any types or is not at
2920 // least as specialized for any types, then the given template is more
2921 // specialized than the other template. Otherwise, neither template is more
2922 // specialized than the other.
2923 Better1 = false;
2924 Better2 = false;
2925 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2926 // C++0x [temp.deduct.partial]p9:
2927 // If, for a given type, deduction succeeds in both directions (i.e., the
2928 // types are identical after the transformations above) and if the type
2929 // from the argument template is more cv-qualified than the type from the
2930 // parameter template (as described above) that type is considered to be
2931 // more specialized than the other. If neither type is more cv-qualified
2932 // than the other then neither type is more specialized than the other.
2933 switch (QualifierComparisons[I]) {
2934 case NeitherMoreQualified:
2935 break;
2936
2937 case ParamMoreQualified:
2938 Better1 = true;
2939 if (Better2)
2940 return 0;
2941 break;
2942
2943 case ArgMoreQualified:
2944 Better2 = true;
2945 if (Better1)
2946 return 0;
2947 break;
2948 }
2949 }
2950
2951 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002952 if (Better1)
2953 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002954 else if (Better2)
2955 return FT2;
2956 else
2957 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002958}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002959
Douglas Gregord5a423b2009-09-25 18:43:00 +00002960/// \brief Determine if the two templates are equivalent.
2961static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2962 if (T1 == T2)
2963 return true;
2964
2965 if (!T1 || !T2)
2966 return false;
2967
2968 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2969}
2970
2971/// \brief Retrieve the most specialized of the given function template
2972/// specializations.
2973///
John McCallc373d482010-01-27 01:50:18 +00002974/// \param SpecBegin the start iterator of the function template
2975/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002976///
John McCallc373d482010-01-27 01:50:18 +00002977/// \param SpecEnd the end iterator of the function template
2978/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002979///
2980/// \param TPOC the partial ordering context to use to compare the function
2981/// template specializations.
2982///
2983/// \param Loc the location where the ambiguity or no-specializations
2984/// diagnostic should occur.
2985///
2986/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2987/// no matching candidates.
2988///
2989/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2990/// occurs.
2991///
2992/// \param CandidateDiag partial diagnostic used for each function template
2993/// specialization that is a candidate in the ambiguous ordering. One parameter
2994/// in this diagnostic should be unbound, which will correspond to the string
2995/// describing the template arguments for the function template specialization.
2996///
2997/// \param Index if non-NULL and the result of this function is non-nULL,
2998/// receives the index corresponding to the resulting function template
2999/// specialization.
3000///
3001/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003002/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003003///
3004/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3005/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003006UnresolvedSetIterator
3007Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3008 UnresolvedSetIterator SpecEnd,
3009 TemplatePartialOrderingContext TPOC,
3010 SourceLocation Loc,
3011 const PartialDiagnostic &NoneDiag,
3012 const PartialDiagnostic &AmbigDiag,
3013 const PartialDiagnostic &CandidateDiag) {
3014 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003015 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003016 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003017 }
3018
John McCallc373d482010-01-27 01:50:18 +00003019 if (SpecBegin + 1 == SpecEnd)
3020 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003021
3022 // Find the function template that is better than all of the templates it
3023 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003024 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003025 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003026 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003027 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003028 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3029 FunctionTemplateDecl *Challenger
3030 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003031 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003032 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003033 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003034 Challenger)) {
3035 Best = I;
3036 BestTemplate = Challenger;
3037 }
3038 }
3039
3040 // Make sure that the "best" function template is more specialized than all
3041 // of the others.
3042 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003043 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3044 FunctionTemplateDecl *Challenger
3045 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003046 if (I != Best &&
3047 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003048 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003049 BestTemplate)) {
3050 Ambiguous = true;
3051 break;
3052 }
3053 }
3054
3055 if (!Ambiguous) {
3056 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003057 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003058 }
3059
3060 // Diagnose the ambiguity.
3061 Diag(Loc, AmbigDiag);
3062
3063 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003064 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3065 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003066 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003067 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3068 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003069
John McCallc373d482010-01-27 01:50:18 +00003070 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003071}
3072
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003073/// \brief Returns the more specialized class template partial specialization
3074/// according to the rules of partial ordering of class template partial
3075/// specializations (C++ [temp.class.order]).
3076///
3077/// \param PS1 the first class template partial specialization
3078///
3079/// \param PS2 the second class template partial specialization
3080///
3081/// \returns the more specialized class template partial specialization. If
3082/// neither partial specialization is more specialized, returns NULL.
3083ClassTemplatePartialSpecializationDecl *
3084Sema::getMoreSpecializedPartialSpecialization(
3085 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003086 ClassTemplatePartialSpecializationDecl *PS2,
3087 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003088 // C++ [temp.class.order]p1:
3089 // For two class template partial specializations, the first is at least as
3090 // specialized as the second if, given the following rewrite to two
3091 // function templates, the first function template is at least as
3092 // specialized as the second according to the ordering rules for function
3093 // templates (14.6.6.2):
3094 // - the first function template has the same template parameters as the
3095 // first partial specialization and has a single function parameter
3096 // whose type is a class template specialization with the template
3097 // arguments of the first partial specialization, and
3098 // - the second function template has the same template parameters as the
3099 // second partial specialization and has a single function parameter
3100 // whose type is a class template specialization with the template
3101 // arguments of the second partial specialization.
3102 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003103 // Rather than synthesize function templates, we merely perform the
3104 // equivalent partial ordering by performing deduction directly on
3105 // the template arguments of the class template partial
3106 // specializations. This computation is slightly simpler than the
3107 // general problem of function template partial ordering, because
3108 // class template partial specializations are more constrained. We
3109 // know that every template parameter is deducible from the class
3110 // template partial specialization's template arguments, for
3111 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003112 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003113 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003114
3115 QualType PT1 = PS1->getInjectedSpecializationType();
3116 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003117
3118 // Determine whether PS1 is at least as specialized as PS2
3119 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003120 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003121 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003122 PT2,
3123 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003124 Info,
3125 Deduced,
3126 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003127 if (Better1) {
3128 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3129 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003130 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3131 PS1->getTemplateArgs(),
3132 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003133 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003134
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003135 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003136 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003137 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003138 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003139 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003140 PT1,
3141 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003142 Info,
3143 Deduced,
3144 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003145 if (Better2) {
3146 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3147 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003148 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3149 PS2->getTemplateArgs(),
3150 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003151 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003152
3153 if (Better1 == Better2)
3154 return 0;
3155
3156 return Better1? PS1 : PS2;
3157}
3158
Mike Stump1eb44332009-09-09 15:08:12 +00003159static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003160MarkUsedTemplateParameters(Sema &SemaRef,
3161 const TemplateArgument &TemplateArg,
3162 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003163 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003164 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003165
Douglas Gregore73bb602009-09-14 21:25:05 +00003166/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003167/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003168static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003169MarkUsedTemplateParameters(Sema &SemaRef,
3170 const Expr *E,
3171 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003172 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003173 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003174 // We can deduce from a pack expansion.
3175 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3176 E = Expansion->getPattern();
3177
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003178 // Skip through any implicit casts we added while type-checking.
3179 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3180 E = ICE->getSubExpr();
3181
Douglas Gregore73bb602009-09-14 21:25:05 +00003182 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3183 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003184 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003185 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003186 return;
3187
Mike Stump1eb44332009-09-09 15:08:12 +00003188 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003189 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3190 if (!NTTP)
3191 return;
3192
Douglas Gregored9c0f92009-10-29 00:04:11 +00003193 if (NTTP->getDepth() == Depth)
3194 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003195}
3196
Douglas Gregore73bb602009-09-14 21:25:05 +00003197/// \brief Mark the template parameters that are used by the given
3198/// nested name specifier.
3199static void
3200MarkUsedTemplateParameters(Sema &SemaRef,
3201 NestedNameSpecifier *NNS,
3202 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003203 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003204 llvm::SmallVectorImpl<bool> &Used) {
3205 if (!NNS)
3206 return;
3207
Douglas Gregored9c0f92009-10-29 00:04:11 +00003208 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3209 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003210 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003211 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003212}
3213
3214/// \brief Mark the template parameters that are used by the given
3215/// template name.
3216static void
3217MarkUsedTemplateParameters(Sema &SemaRef,
3218 TemplateName Name,
3219 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003220 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003221 llvm::SmallVectorImpl<bool> &Used) {
3222 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3223 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003224 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3225 if (TTP->getDepth() == Depth)
3226 Used[TTP->getIndex()] = true;
3227 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003228 return;
3229 }
3230
Douglas Gregor788cd062009-11-11 01:00:40 +00003231 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3232 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3233 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003234 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003235 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3236 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003237}
3238
3239/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003240/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003241static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003242MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3243 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003244 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003245 llvm::SmallVectorImpl<bool> &Used) {
3246 if (T.isNull())
3247 return;
3248
Douglas Gregor031a5882009-06-13 00:26:55 +00003249 // Non-dependent types have nothing deducible
3250 if (!T->isDependentType())
3251 return;
3252
3253 T = SemaRef.Context.getCanonicalType(T);
3254 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003255 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003256 MarkUsedTemplateParameters(SemaRef,
3257 cast<PointerType>(T)->getPointeeType(),
3258 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003259 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003260 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003261 break;
3262
3263 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003264 MarkUsedTemplateParameters(SemaRef,
3265 cast<BlockPointerType>(T)->getPointeeType(),
3266 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003267 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003268 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003269 break;
3270
3271 case Type::LValueReference:
3272 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003273 MarkUsedTemplateParameters(SemaRef,
3274 cast<ReferenceType>(T)->getPointeeType(),
3275 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003276 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003277 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003278 break;
3279
3280 case Type::MemberPointer: {
3281 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003282 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003283 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003284 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003285 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003286 break;
3287 }
3288
3289 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003290 MarkUsedTemplateParameters(SemaRef,
3291 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003292 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003293 // Fall through to check the element type
3294
3295 case Type::ConstantArray:
3296 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003297 MarkUsedTemplateParameters(SemaRef,
3298 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003299 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003300 break;
3301
3302 case Type::Vector:
3303 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003304 MarkUsedTemplateParameters(SemaRef,
3305 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003306 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003307 break;
3308
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003309 case Type::DependentSizedExtVector: {
3310 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003311 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003312 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003313 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003314 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003315 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003316 break;
3317 }
3318
Douglas Gregor031a5882009-06-13 00:26:55 +00003319 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003320 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003321 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003322 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003323 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003324 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003325 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003326 break;
3327 }
3328
Douglas Gregored9c0f92009-10-29 00:04:11 +00003329 case Type::TemplateTypeParm: {
3330 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3331 if (TTP->getDepth() == Depth)
3332 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003333 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003334 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003335
John McCall31f17ec2010-04-27 00:57:59 +00003336 case Type::InjectedClassName:
3337 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3338 // fall through
3339
Douglas Gregor031a5882009-06-13 00:26:55 +00003340 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003341 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003342 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003343 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003344 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003345
3346 // C++0x [temp.deduct.type]p9:
3347 // If the template argument list of P contains a pack expansion that is not
3348 // the last template argument, the entire template argument list is a
3349 // non-deduced context.
3350 if (OnlyDeduced &&
3351 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3352 break;
3353
Douglas Gregore73bb602009-09-14 21:25:05 +00003354 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003355 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3356 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003357 break;
3358 }
3359
Douglas Gregore73bb602009-09-14 21:25:05 +00003360 case Type::Complex:
3361 if (!OnlyDeduced)
3362 MarkUsedTemplateParameters(SemaRef,
3363 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003364 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003365 break;
3366
Douglas Gregor4714c122010-03-31 17:34:00 +00003367 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003368 if (!OnlyDeduced)
3369 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003370 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003371 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003372 break;
3373
John McCall33500952010-06-11 00:33:02 +00003374 case Type::DependentTemplateSpecialization: {
3375 const DependentTemplateSpecializationType *Spec
3376 = cast<DependentTemplateSpecializationType>(T);
3377 if (!OnlyDeduced)
3378 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3379 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003380
3381 // C++0x [temp.deduct.type]p9:
3382 // If the template argument list of P contains a pack expansion that is not
3383 // the last template argument, the entire template argument list is a
3384 // non-deduced context.
3385 if (OnlyDeduced &&
3386 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3387 break;
3388
John McCall33500952010-06-11 00:33:02 +00003389 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3390 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3391 Used);
3392 break;
3393 }
3394
John McCallad5e7382010-03-01 23:49:17 +00003395 case Type::TypeOf:
3396 if (!OnlyDeduced)
3397 MarkUsedTemplateParameters(SemaRef,
3398 cast<TypeOfType>(T)->getUnderlyingType(),
3399 OnlyDeduced, Depth, Used);
3400 break;
3401
3402 case Type::TypeOfExpr:
3403 if (!OnlyDeduced)
3404 MarkUsedTemplateParameters(SemaRef,
3405 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3406 OnlyDeduced, Depth, Used);
3407 break;
3408
3409 case Type::Decltype:
3410 if (!OnlyDeduced)
3411 MarkUsedTemplateParameters(SemaRef,
3412 cast<DecltypeType>(T)->getUnderlyingExpr(),
3413 OnlyDeduced, Depth, Used);
3414 break;
3415
Douglas Gregor7536dd52010-12-20 02:24:11 +00003416 case Type::PackExpansion:
3417 MarkUsedTemplateParameters(SemaRef,
3418 cast<PackExpansionType>(T)->getPattern(),
3419 OnlyDeduced, Depth, Used);
3420 break;
3421
Douglas Gregore73bb602009-09-14 21:25:05 +00003422 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003423 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003424 case Type::VariableArray:
3425 case Type::FunctionNoProto:
3426 case Type::Record:
3427 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003428 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003429 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003430 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003431 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003432#define TYPE(Class, Base)
3433#define ABSTRACT_TYPE(Class, Base)
3434#define DEPENDENT_TYPE(Class, Base)
3435#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3436#include "clang/AST/TypeNodes.def"
3437 break;
3438 }
3439}
3440
Douglas Gregore73bb602009-09-14 21:25:05 +00003441/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003442/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003443static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003444MarkUsedTemplateParameters(Sema &SemaRef,
3445 const TemplateArgument &TemplateArg,
3446 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003447 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003448 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003449 switch (TemplateArg.getKind()) {
3450 case TemplateArgument::Null:
3451 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003452 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003453 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor031a5882009-06-13 00:26:55 +00003455 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003456 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003457 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003458 break;
3459
Douglas Gregor788cd062009-11-11 01:00:40 +00003460 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003461 case TemplateArgument::TemplateExpansion:
3462 MarkUsedTemplateParameters(SemaRef,
3463 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003464 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003465 break;
3466
3467 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003468 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003469 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003470 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003471
Anders Carlssond01b1da2009-06-15 17:04:53 +00003472 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003473 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3474 PEnd = TemplateArg.pack_end();
3475 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003476 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003477 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003478 }
3479}
3480
3481/// \brief Mark the template parameters can be deduced by the given
3482/// template argument list.
3483///
3484/// \param TemplateArgs the template argument list from which template
3485/// parameters will be deduced.
3486///
3487/// \param Deduced a bit vector whose elements will be set to \c true
3488/// to indicate when the corresponding template parameter will be
3489/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003490void
Douglas Gregore73bb602009-09-14 21:25:05 +00003491Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003492 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003493 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003494 // C++0x [temp.deduct.type]p9:
3495 // If the template argument list of P contains a pack expansion that is not
3496 // the last template argument, the entire template argument list is a
3497 // non-deduced context.
3498 if (OnlyDeduced &&
3499 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3500 return;
3501
Douglas Gregor031a5882009-06-13 00:26:55 +00003502 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003503 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3504 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003505}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003506
3507/// \brief Marks all of the template parameters that will be deduced by a
3508/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003509void
3510Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3511 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003512 TemplateParameterList *TemplateParams
3513 = FunctionTemplate->getTemplateParameters();
3514 Deduced.clear();
3515 Deduced.resize(TemplateParams->size());
3516
3517 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3518 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3519 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003520 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003521}