blob: deb5457d857773b8c82f554bb71ab6cf3e7169ba [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
13#include "Sema.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Parse/DeclSpec.h"
20#include "llvm/Support/Compiler.h"
Douglas Gregor508f1c82009-06-26 23:10:12 +000021
22namespace clang {
23 /// \brief Various flags that control template argument deduction.
24 ///
25 /// These flags can be bitwise-OR'd together.
26 enum TemplateDeductionFlags {
27 /// \brief No template argument deduction flags, which indicates the
28 /// strictest results for template argument deduction (as used for, e.g.,
29 /// matching class template partial specializations).
30 TDF_None = 0,
31 /// \brief Within template argument deduction from a function call, we are
32 /// matching with a parameter type for which the original parameter was
33 /// a reference.
34 TDF_ParamWithReferenceType = 0x1,
35 /// \brief Within template argument deduction from a function call, we
36 /// are matching in a case where we ignore cv-qualifiers.
37 TDF_IgnoreQualifiers = 0x02,
38 /// \brief Within template argument deduction from a function call,
39 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000040 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor508f1c82009-06-26 23:10:12 +000041 TDF_DerivedClass = 0x04
42 };
43}
44
Douglas Gregor0b9247f2009-06-04 00:03:07 +000045using namespace clang;
46
Douglas Gregorf67875d2009-06-12 18:26:56 +000047static Sema::TemplateDeductionResult
48DeduceTemplateArguments(ASTContext &Context,
49 TemplateParameterList *TemplateParams,
50 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000051 const TemplateArgument &Arg,
Douglas Gregorf67875d2009-06-12 18:26:56 +000052 Sema::TemplateDeductionInfo &Info,
Douglas Gregord708c722009-06-09 16:35:58 +000053 llvm::SmallVectorImpl<TemplateArgument> &Deduced);
54
Douglas Gregor199d9912009-06-05 00:53:49 +000055/// \brief If the given expression is of a form that permits the deduction
56/// of a non-type template parameter, return the declaration of that
57/// non-type template parameter.
58static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
59 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
60 E = IC->getSubExpr();
61
62 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
63 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
64
65 return 0;
66}
67
68/// \brief Deduce the value of the given non-type template parameter
69/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +000070static Sema::TemplateDeductionResult
71DeduceNonTypeTemplateArgument(ASTContext &Context,
72 NonTypeTemplateParmDecl *NTTP,
Anders Carlsson335e24a2009-06-16 22:44:31 +000073 llvm::APSInt Value,
Douglas Gregorf67875d2009-06-12 18:26:56 +000074 Sema::TemplateDeductionInfo &Info,
75 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor199d9912009-06-05 00:53:49 +000076 assert(NTTP->getDepth() == 0 &&
77 "Cannot deduce non-type template argument with depth > 0");
78
79 if (Deduced[NTTP->getIndex()].isNull()) {
Anders Carlsson25af1ed2009-06-16 23:08:29 +000080 QualType T = NTTP->getType();
81
82 // FIXME: Make sure we didn't overflow our data type!
83 unsigned AllowedBits = Context.getTypeSize(T);
84 if (Value.getBitWidth() != AllowedBits)
85 Value.extOrTrunc(AllowedBits);
86 Value.setIsSigned(T->isSignedIntegerType());
87
88 Deduced[NTTP->getIndex()] = TemplateArgument(SourceLocation(), Value, T);
Douglas Gregorf67875d2009-06-12 18:26:56 +000089 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +000090 }
91
Douglas Gregorf67875d2009-06-12 18:26:56 +000092 assert(Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral);
Douglas Gregor199d9912009-06-05 00:53:49 +000093
94 // If the template argument was previously deduced to a negative value,
95 // then our deduction fails.
96 const llvm::APSInt *PrevValuePtr = Deduced[NTTP->getIndex()].getAsIntegral();
Anders Carlsson335e24a2009-06-16 22:44:31 +000097 if (PrevValuePtr->isNegative()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +000098 Info.Param = NTTP;
99 Info.FirstArg = Deduced[NTTP->getIndex()];
Anders Carlsson335e24a2009-06-16 22:44:31 +0000100 Info.SecondArg = TemplateArgument(SourceLocation(), Value, NTTP->getType());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000101 return Sema::TDK_Inconsistent;
102 }
103
Anders Carlsson335e24a2009-06-16 22:44:31 +0000104 llvm::APSInt PrevValue = *PrevValuePtr;
Douglas Gregor199d9912009-06-05 00:53:49 +0000105 if (Value.getBitWidth() > PrevValue.getBitWidth())
106 PrevValue.zext(Value.getBitWidth());
107 else if (Value.getBitWidth() < PrevValue.getBitWidth())
108 Value.zext(PrevValue.getBitWidth());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000109
110 if (Value != PrevValue) {
111 Info.Param = NTTP;
112 Info.FirstArg = Deduced[NTTP->getIndex()];
Anders Carlsson335e24a2009-06-16 22:44:31 +0000113 Info.SecondArg = TemplateArgument(SourceLocation(), Value, NTTP->getType());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000114 return Sema::TDK_Inconsistent;
115 }
116
117 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000118}
119
120/// \brief Deduce the value of the given non-type template parameter
121/// from the given type- or value-dependent expression.
122///
123/// \returns true if deduction succeeded, false otherwise.
124
Douglas Gregorf67875d2009-06-12 18:26:56 +0000125static Sema::TemplateDeductionResult
126DeduceNonTypeTemplateArgument(ASTContext &Context,
127 NonTypeTemplateParmDecl *NTTP,
128 Expr *Value,
129 Sema::TemplateDeductionInfo &Info,
130 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000131 assert(NTTP->getDepth() == 0 &&
132 "Cannot deduce non-type template argument with depth > 0");
133 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
134 "Expression template argument must be type- or value-dependent.");
135
136 if (Deduced[NTTP->getIndex()].isNull()) {
137 // FIXME: Clone the Value?
138 Deduced[NTTP->getIndex()] = TemplateArgument(Value);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000139 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000140 }
141
142 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
143 // Okay, we deduced a constant in one case and a dependent expression
144 // in another case. FIXME: Later, we will check that instantiating the
145 // dependent expression gives us the constant value.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000146 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000147 }
148
149 // FIXME: Compare the expressions for equality!
Douglas Gregorf67875d2009-06-12 18:26:56 +0000150 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000151}
152
Douglas Gregorf67875d2009-06-12 18:26:56 +0000153static Sema::TemplateDeductionResult
154DeduceTemplateArguments(ASTContext &Context,
155 TemplateName Param,
156 TemplateName Arg,
157 Sema::TemplateDeductionInfo &Info,
158 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000159 // FIXME: Implement template argument deduction for template
160 // template parameters.
161
Douglas Gregorf67875d2009-06-12 18:26:56 +0000162 // FIXME: this routine does not have enough information to produce
163 // good diagnostics.
164
Douglas Gregord708c722009-06-09 16:35:58 +0000165 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
166 TemplateDecl *ArgDecl = Arg.getAsTemplateDecl();
167
Douglas Gregorf67875d2009-06-12 18:26:56 +0000168 if (!ParamDecl || !ArgDecl) {
169 // FIXME: fill in Info.Param/Info.FirstArg
170 return Sema::TDK_Inconsistent;
171 }
Douglas Gregord708c722009-06-09 16:35:58 +0000172
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000173 ParamDecl = cast<TemplateDecl>(ParamDecl->getCanonicalDecl());
174 ArgDecl = cast<TemplateDecl>(ArgDecl->getCanonicalDecl());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000175 if (ParamDecl != ArgDecl) {
176 // FIXME: fill in Info.Param/Info.FirstArg
177 return Sema::TDK_Inconsistent;
178 }
179
180 return Sema::TDK_Success;
Douglas Gregord708c722009-06-09 16:35:58 +0000181}
182
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000183/// \brief Deduce the template arguments by comparing the template parameter
184/// type (which is a template-id) with the template argument type.
185///
186/// \param Context the AST context in which this deduction occurs.
187///
188/// \param TemplateParams the template parameters that we are deducing
189///
190/// \param Param the parameter type
191///
192/// \param Arg the argument type
193///
194/// \param Info information about the template argument deduction itself
195///
196/// \param Deduced the deduced template arguments
197///
198/// \returns the result of template argument deduction so far. Note that a
199/// "success" result means that template argument deduction has not yet failed,
200/// but it may still fail, later, for other reasons.
201static Sema::TemplateDeductionResult
202DeduceTemplateArguments(ASTContext &Context,
203 TemplateParameterList *TemplateParams,
204 const TemplateSpecializationType *Param,
205 QualType Arg,
206 Sema::TemplateDeductionInfo &Info,
207 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
208 assert(Arg->isCanonical() && "Argument type must be canonical");
209
210 // Check whether the template argument is a dependent template-id.
211 // FIXME: This is untested code; it can be tested when we implement
212 // partial ordering of class template partial specializations.
213 if (const TemplateSpecializationType *SpecArg
214 = dyn_cast<TemplateSpecializationType>(Arg)) {
215 // Perform template argument deduction for the template name.
216 if (Sema::TemplateDeductionResult Result
217 = DeduceTemplateArguments(Context,
218 Param->getTemplateName(),
219 SpecArg->getTemplateName(),
220 Info, Deduced))
221 return Result;
222
223 unsigned NumArgs = Param->getNumArgs();
224
225 // FIXME: When one of the template-names refers to a
226 // declaration with default template arguments, do we need to
227 // fill in those default template arguments here? Most likely,
228 // the answer is "yes", but I don't see any references. This
229 // issue may be resolved elsewhere, because we may want to
230 // instantiate default template arguments when we actually write
231 // the template-id.
232 if (SpecArg->getNumArgs() != NumArgs)
233 return Sema::TDK_NonDeducedMismatch;
234
235 // Perform template argument deduction on each template
236 // argument.
237 for (unsigned I = 0; I != NumArgs; ++I)
238 if (Sema::TemplateDeductionResult Result
239 = DeduceTemplateArguments(Context, TemplateParams,
240 Param->getArg(I),
241 SpecArg->getArg(I),
242 Info, Deduced))
243 return Result;
244
245 return Sema::TDK_Success;
246 }
247
248 // If the argument type is a class template specialization, we
249 // perform template argument deduction using its template
250 // arguments.
251 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
252 if (!RecordArg)
253 return Sema::TDK_NonDeducedMismatch;
254
255 ClassTemplateSpecializationDecl *SpecArg
256 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
257 if (!SpecArg)
258 return Sema::TDK_NonDeducedMismatch;
259
260 // Perform template argument deduction for the template name.
261 if (Sema::TemplateDeductionResult Result
262 = DeduceTemplateArguments(Context,
263 Param->getTemplateName(),
264 TemplateName(SpecArg->getSpecializedTemplate()),
265 Info, Deduced))
266 return Result;
267
268 // FIXME: Can the # of arguments in the parameter and the argument
269 // differ due to default arguments?
270 unsigned NumArgs = Param->getNumArgs();
271 const TemplateArgumentList &ArgArgs = SpecArg->getTemplateArgs();
272 if (NumArgs != ArgArgs.size())
273 return Sema::TDK_NonDeducedMismatch;
274
275 for (unsigned I = 0; I != NumArgs; ++I)
276 if (Sema::TemplateDeductionResult Result
277 = DeduceTemplateArguments(Context, TemplateParams,
278 Param->getArg(I),
279 ArgArgs.get(I),
280 Info, Deduced))
281 return Result;
282
283 return Sema::TDK_Success;
284}
285
Douglas Gregor500d3312009-06-26 18:27:22 +0000286/// \brief Deduce the template arguments by comparing the parameter type and
287/// the argument type (C++ [temp.deduct.type]).
288///
289/// \param Context the AST context in which this deduction occurs.
290///
291/// \param TemplateParams the template parameters that we are deducing
292///
293/// \param ParamIn the parameter type
294///
295/// \param ArgIn the argument type
296///
297/// \param Info information about the template argument deduction itself
298///
299/// \param Deduced the deduced template arguments
300///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000301/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
302/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000303///
304/// \returns the result of template argument deduction so far. Note that a
305/// "success" result means that template argument deduction has not yet failed,
306/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000307static Sema::TemplateDeductionResult
308DeduceTemplateArguments(ASTContext &Context,
309 TemplateParameterList *TemplateParams,
310 QualType ParamIn, QualType ArgIn,
311 Sema::TemplateDeductionInfo &Info,
Douglas Gregor500d3312009-06-26 18:27:22 +0000312 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000313 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000314 // We only want to look at the canonical types, since typedefs and
315 // sugar are not part of template argument deduction.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000316 QualType Param = Context.getCanonicalType(ParamIn);
317 QualType Arg = Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000318
Douglas Gregor500d3312009-06-26 18:27:22 +0000319 // C++0x [temp.deduct.call]p4 bullet 1:
320 // - If the original P is a reference type, the deduced A (i.e., the type
321 // referred to by the reference) can be more cv-qualified than the
322 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000323 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor500d3312009-06-26 18:27:22 +0000324 unsigned ExtraQualsOnParam
325 = Param.getCVRQualifiers() & ~Arg.getCVRQualifiers();
326 Param.setCVRQualifiers(Param.getCVRQualifiers() & ~ExtraQualsOnParam);
327 }
328
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000329 // If the parameter type is not dependent, there is nothing to deduce.
330 if (!Param->isDependentType())
331 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000332
Douglas Gregor199d9912009-06-05 00:53:49 +0000333 // C++ [temp.deduct.type]p9:
Douglas Gregor199d9912009-06-05 00:53:49 +0000334 // A template type argument T, a template template argument TT or a
335 // template non-type argument i can be deduced if P and A have one of
336 // the following forms:
337 //
338 // T
339 // cv-list T
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000340 if (const TemplateTypeParmType *TemplateTypeParm
341 = Param->getAsTemplateTypeParmType()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 unsigned Index = TemplateTypeParm->getIndex();
343
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000344 // If the argument type is an array type, move the qualifiers up to the
345 // top level, so they can be matched with the qualifiers on the parameter.
346 // FIXME: address spaces, ObjC GC qualifiers
347 QualType ArgElementType = Arg;
348 while (const ArrayType *ArgArray = ArgElementType->getAs<ArrayType>())
349 ArgElementType = ArgArray->getElementType();
350 Arg = Arg.getWithAdditionalQualifiers(ArgElementType.getCVRQualifiers());
351
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000352 // The argument type can not be less qualified than the parameter
353 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000354 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000355 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
356 Info.FirstArg = Deduced[Index];
357 Info.SecondArg = TemplateArgument(SourceLocation(), Arg);
358 return Sema::TDK_InconsistentQuals;
359 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000360
361 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
362
363 unsigned Quals = Arg.getCVRQualifiers() & ~Param.getCVRQualifiers();
Douglas Gregorb084a052009-07-22 20:25:36 +0000364 QualType DeducedType
365 = Context.getCanonicalType(Arg.getQualifiedType(Quals));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000366
367 if (Deduced[Index].isNull())
368 Deduced[Index] = TemplateArgument(SourceLocation(), DeducedType);
369 else {
370 // C++ [temp.deduct.type]p2:
371 // [...] If type deduction cannot be done for any P/A pair, or if for
372 // any pair the deduction leads to more than one possible set of
373 // deduced values, or if different pairs yield different deduced
374 // values, or if any template argument remains neither deduced nor
375 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000376 if (Deduced[Index].getAsType() != DeducedType) {
377 Info.Param
378 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
379 Info.FirstArg = Deduced[Index];
380 Info.SecondArg = TemplateArgument(SourceLocation(), Arg);
381 return Sema::TDK_Inconsistent;
382 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000383 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000384 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000385 }
386
Douglas Gregorf67875d2009-06-12 18:26:56 +0000387 // Set up the template argument deduction information for a failure.
388 Info.FirstArg = TemplateArgument(SourceLocation(), ParamIn);
389 Info.SecondArg = TemplateArgument(SourceLocation(), ArgIn);
390
Douglas Gregor508f1c82009-06-26 23:10:12 +0000391 // Check the cv-qualifiers on the parameter and argument types.
392 if (!(TDF & TDF_IgnoreQualifiers)) {
393 if (TDF & TDF_ParamWithReferenceType) {
394 if (Param.isMoreQualifiedThan(Arg))
395 return Sema::TDK_NonDeducedMismatch;
396 } else {
397 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
398 return Sema::TDK_NonDeducedMismatch;
399 }
400 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000401
Douglas Gregord560d502009-06-04 00:21:18 +0000402 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000403 // No deduction possible for these types
404 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000405 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000406
407 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000408 case Type::Pointer: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000409 const PointerType *PointerArg = Arg->getAsPointerType();
Douglas Gregord560d502009-06-04 00:21:18 +0000410 if (!PointerArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000411 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000412
Douglas Gregor41128772009-06-26 23:27:24 +0000413 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000414 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000415 cast<PointerType>(Param)->getPointeeType(),
416 PointerArg->getPointeeType(),
Douglas Gregor41128772009-06-26 23:27:24 +0000417 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000418 }
419
Douglas Gregor199d9912009-06-05 00:53:49 +0000420 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000421 case Type::LValueReference: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000422 const LValueReferenceType *ReferenceArg = Arg->getAsLValueReferenceType();
Douglas Gregord560d502009-06-04 00:21:18 +0000423 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000424 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000425
Douglas Gregorf67875d2009-06-12 18:26:56 +0000426 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000427 cast<LValueReferenceType>(Param)->getPointeeType(),
428 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000429 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000430 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000431
Douglas Gregor199d9912009-06-05 00:53:49 +0000432 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000433 case Type::RValueReference: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000434 const RValueReferenceType *ReferenceArg = Arg->getAsRValueReferenceType();
Douglas Gregord560d502009-06-04 00:21:18 +0000435 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000436 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000437
Douglas Gregorf67875d2009-06-12 18:26:56 +0000438 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000439 cast<RValueReferenceType>(Param)->getPointeeType(),
440 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000441 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000442 }
443
Douglas Gregor199d9912009-06-05 00:53:49 +0000444 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000445 case Type::IncompleteArray: {
446 const IncompleteArrayType *IncompleteArrayArg =
447 Context.getAsIncompleteArrayType(Arg);
448 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000449 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000450
Douglas Gregorf67875d2009-06-12 18:26:56 +0000451 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000452 Context.getAsIncompleteArrayType(Param)->getElementType(),
453 IncompleteArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000454 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000455 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000456
457 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000458 case Type::ConstantArray: {
459 const ConstantArrayType *ConstantArrayArg =
460 Context.getAsConstantArrayType(Arg);
461 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000462 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000463
464 const ConstantArrayType *ConstantArrayParm =
465 Context.getAsConstantArrayType(Param);
466 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000467 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000468
Douglas Gregorf67875d2009-06-12 18:26:56 +0000469 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000470 ConstantArrayParm->getElementType(),
471 ConstantArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000472 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000473 }
474
Douglas Gregor199d9912009-06-05 00:53:49 +0000475 // type [i]
476 case Type::DependentSizedArray: {
477 const ArrayType *ArrayArg = dyn_cast<ArrayType>(Arg);
478 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000479 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000480
481 // Check the element type of the arrays
482 const DependentSizedArrayType *DependentArrayParm
483 = cast<DependentSizedArrayType>(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000484 if (Sema::TemplateDeductionResult Result
485 = DeduceTemplateArguments(Context, TemplateParams,
486 DependentArrayParm->getElementType(),
487 ArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000488 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000489 return Result;
Douglas Gregor199d9912009-06-05 00:53:49 +0000490
491 // Determine the array bound is something we can deduce.
492 NonTypeTemplateParmDecl *NTTP
493 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
494 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000495 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000496
497 // We can perform template argument deduction for the given non-type
498 // template parameter.
499 assert(NTTP->getDepth() == 0 &&
500 "Cannot deduce non-type template argument at depth > 0");
501 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000502 = dyn_cast<ConstantArrayType>(ArrayArg)) {
503 llvm::APSInt Size(ConstantArrayArg->getSize());
504 return DeduceNonTypeTemplateArgument(Context, NTTP, Size,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000505 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000506 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000507 if (const DependentSizedArrayType *DependentArrayArg
508 = dyn_cast<DependentSizedArrayType>(ArrayArg))
509 return DeduceNonTypeTemplateArgument(Context, NTTP,
510 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000511 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000512
513 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000514 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000515 }
516
Douglas Gregor0fce0ae2009-06-08 15:59:14 +0000517 // type(*)(T)
518 // T(*)()
519 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000520 case Type::FunctionProto: {
521 const FunctionProtoType *FunctionProtoArg =
522 dyn_cast<FunctionProtoType>(Arg);
523 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000524 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000525
526 const FunctionProtoType *FunctionProtoParam =
527 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000528
529 if (FunctionProtoParam->getTypeQuals() !=
530 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000531 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000532
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000533 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000534 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000535
536 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000537 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000538
Anders Carlssona27fad52009-06-08 15:19:08 +0000539 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000540 if (Sema::TemplateDeductionResult Result
541 = DeduceTemplateArguments(Context, TemplateParams,
542 FunctionProtoParam->getResultType(),
543 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000544 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000545 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000546
Anders Carlssona27fad52009-06-08 15:19:08 +0000547 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
548 // Check argument types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000549 if (Sema::TemplateDeductionResult Result
550 = DeduceTemplateArguments(Context, TemplateParams,
551 FunctionProtoParam->getArgType(I),
552 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000553 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000554 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000555 }
556
Douglas Gregorf67875d2009-06-12 18:26:56 +0000557 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000558 }
Douglas Gregord708c722009-06-09 16:35:58 +0000559
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000560 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000561 // template-name<i>
562 // TT<T> (TODO)
563 // TT<i> (TODO)
564 // TT<> (TODO)
565 case Type::TemplateSpecialization: {
566 const TemplateSpecializationType *SpecParam
567 = cast<TemplateSpecializationType>(Param);
Anders Carlssona27fad52009-06-08 15:19:08 +0000568
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000569 // Try to deduce template arguments from the template-id.
570 Sema::TemplateDeductionResult Result
571 = DeduceTemplateArguments(Context, TemplateParams, SpecParam, Arg,
572 Info, Deduced);
573
574 if (Result && (TDF & TDF_DerivedClass) &&
575 Result != Sema::TDK_Inconsistent) {
576 // C++ [temp.deduct.call]p3b3:
577 // If P is a class, and P has the form template-id, then A can be a
578 // derived class of the deduced A. Likewise, if P is a pointer to a
579 // class of the form template-id, A can be a pointer to a derived
580 // class pointed to by the deduced A.
581 //
582 // More importantly:
583 // These alternatives are considered only if type deduction would
584 // otherwise fail.
585 if (const RecordType *RecordT = dyn_cast<RecordType>(Arg)) {
586 // Use data recursion to crawl through the list of base classes.
587 // Visited contains the set of nodes we have already visited, while
588 // ToVisit is our stack of records that we still need to visit.
589 llvm::SmallPtrSet<const RecordType *, 8> Visited;
590 llvm::SmallVector<const RecordType *, 8> ToVisit;
591 ToVisit.push_back(RecordT);
592 bool Successful = false;
593 while (!ToVisit.empty()) {
594 // Retrieve the next class in the inheritance hierarchy.
595 const RecordType *NextT = ToVisit.back();
596 ToVisit.pop_back();
597
598 // If we have already seen this type, skip it.
599 if (!Visited.insert(NextT))
600 continue;
601
602 // If this is a base class, try to perform template argument
603 // deduction from it.
604 if (NextT != RecordT) {
605 Sema::TemplateDeductionResult BaseResult
606 = DeduceTemplateArguments(Context, TemplateParams, SpecParam,
607 QualType(NextT, 0), Info, Deduced);
608
609 // If template argument deduction for this base was successful,
610 // note that we had some success.
611 if (BaseResult == Sema::TDK_Success)
612 Successful = true;
613 // If deduction against this base resulted in an inconsistent
614 // set of deduced template arguments, template argument
615 // deduction fails.
616 else if (BaseResult == Sema::TDK_Inconsistent)
617 return BaseResult;
618 }
619
620 // Visit base classes
621 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
622 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
623 BaseEnd = Next->bases_end();
624 Base != BaseEnd; ++Base) {
625 assert(Base->getType()->isRecordType() &&
626 "Base class that isn't a record?");
Ted Kremenek35366a62009-07-17 17:50:17 +0000627 ToVisit.push_back(Base->getType()->getAsRecordType());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000628 }
629 }
630
631 if (Successful)
632 return Sema::TDK_Success;
633 }
634
635 }
636
637 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000638 }
639
Douglas Gregor637a4092009-06-10 23:47:09 +0000640 // T type::*
641 // T T::*
642 // T (type::*)()
643 // type (T::*)()
644 // type (type::*)(T)
645 // type (T::*)(T)
646 // T (type::*)(T)
647 // T (T::*)()
648 // T (T::*)(T)
649 case Type::MemberPointer: {
650 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
651 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
652 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000653 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000654
Douglas Gregorf67875d2009-06-12 18:26:56 +0000655 if (Sema::TemplateDeductionResult Result
656 = DeduceTemplateArguments(Context, TemplateParams,
657 MemPtrParam->getPointeeType(),
658 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000659 Info, Deduced,
660 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000661 return Result;
662
663 return DeduceTemplateArguments(Context, TemplateParams,
664 QualType(MemPtrParam->getClass(), 0),
665 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000666 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000667 }
668
Anders Carlsson9a917e42009-06-12 22:56:54 +0000669 // (clang extension)
670 //
Anders Carlsson859ba502009-06-12 16:23:10 +0000671 // type(^)(T)
672 // T(^)()
673 // T(^)(T)
674 case Type::BlockPointer: {
675 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
676 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
677
678 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000679 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson859ba502009-06-12 16:23:10 +0000680
Douglas Gregorf67875d2009-06-12 18:26:56 +0000681 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000682 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000683 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000684 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000685 }
686
Douglas Gregor637a4092009-06-10 23:47:09 +0000687 case Type::TypeOfExpr:
688 case Type::TypeOf:
689 case Type::Typename:
690 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000691 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000692
Douglas Gregord560d502009-06-04 00:21:18 +0000693 default:
694 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000695 }
696
697 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000698 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000699}
700
Douglas Gregorf67875d2009-06-12 18:26:56 +0000701static Sema::TemplateDeductionResult
702DeduceTemplateArguments(ASTContext &Context,
703 TemplateParameterList *TemplateParams,
704 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000705 const TemplateArgument &Arg,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000706 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000707 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000708 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000709 case TemplateArgument::Null:
710 assert(false && "Null template argument in parameter list");
711 break;
712
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000713 case TemplateArgument::Type:
Douglas Gregor199d9912009-06-05 00:53:49 +0000714 assert(Arg.getKind() == TemplateArgument::Type && "Type/value mismatch");
Douglas Gregor508f1c82009-06-26 23:10:12 +0000715 return DeduceTemplateArguments(Context, TemplateParams, Param.getAsType(),
716 Arg.getAsType(), Info, Deduced, 0);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000717
Douglas Gregor199d9912009-06-05 00:53:49 +0000718 case TemplateArgument::Declaration:
719 // FIXME: Implement this check
720 assert(false && "Unimplemented template argument deduction case");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000721 Info.FirstArg = Param;
722 Info.SecondArg = Arg;
723 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000724
725 case TemplateArgument::Integral:
726 if (Arg.getKind() == TemplateArgument::Integral) {
727 // FIXME: Zero extension + sign checking here?
Douglas Gregorf67875d2009-06-12 18:26:56 +0000728 if (*Param.getAsIntegral() == *Arg.getAsIntegral())
729 return Sema::TDK_Success;
730
731 Info.FirstArg = Param;
732 Info.SecondArg = Arg;
733 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000734 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000735
736 if (Arg.getKind() == TemplateArgument::Expression) {
737 Info.FirstArg = Param;
738 Info.SecondArg = Arg;
739 return Sema::TDK_NonDeducedMismatch;
740 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000741
742 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000743 Info.FirstArg = Param;
744 Info.SecondArg = Arg;
745 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000746
747 case TemplateArgument::Expression: {
748 if (NonTypeTemplateParmDecl *NTTP
749 = getDeducedParameterFromExpr(Param.getAsExpr())) {
750 if (Arg.getKind() == TemplateArgument::Integral)
751 // FIXME: Sign problems here
752 return DeduceNonTypeTemplateArgument(Context, NTTP,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000753 *Arg.getAsIntegral(),
754 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000755 if (Arg.getKind() == TemplateArgument::Expression)
756 return DeduceNonTypeTemplateArgument(Context, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000757 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000758
759 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000760 Info.FirstArg = Param;
761 Info.SecondArg = Arg;
762 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000763 }
764
765 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000766 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000767 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000768 case TemplateArgument::Pack:
769 assert(0 && "FIXME: Implement!");
770 break;
Douglas Gregor199d9912009-06-05 00:53:49 +0000771 }
772
Douglas Gregorf67875d2009-06-12 18:26:56 +0000773 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000774}
775
Douglas Gregorf67875d2009-06-12 18:26:56 +0000776static Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000777DeduceTemplateArguments(ASTContext &Context,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000778 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000779 const TemplateArgumentList &ParamList,
780 const TemplateArgumentList &ArgList,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000781 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000782 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
783 assert(ParamList.size() == ArgList.size());
784 for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000785 if (Sema::TemplateDeductionResult Result
786 = DeduceTemplateArguments(Context, TemplateParams,
787 ParamList[I], ArgList[I],
788 Info, Deduced))
789 return Result;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000790 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000791 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000792}
793
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000794/// \brief Determine whether two template arguments are the same.
795static bool isSameTemplateArg(ASTContext &Context,
796 const TemplateArgument &X,
797 const TemplateArgument &Y) {
798 if (X.getKind() != Y.getKind())
799 return false;
800
801 switch (X.getKind()) {
802 case TemplateArgument::Null:
803 assert(false && "Comparing NULL template argument");
804 break;
805
806 case TemplateArgument::Type:
807 return Context.getCanonicalType(X.getAsType()) ==
808 Context.getCanonicalType(Y.getAsType());
809
810 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000811 return X.getAsDecl()->getCanonicalDecl() ==
812 Y.getAsDecl()->getCanonicalDecl();
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000813
814 case TemplateArgument::Integral:
815 return *X.getAsIntegral() == *Y.getAsIntegral();
816
817 case TemplateArgument::Expression:
818 // FIXME: We assume that all expressions are distinct, but we should
819 // really check their canonical forms.
820 return false;
821
822 case TemplateArgument::Pack:
823 if (X.pack_size() != Y.pack_size())
824 return false;
825
826 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
827 XPEnd = X.pack_end(),
828 YP = Y.pack_begin();
829 XP != XPEnd; ++XP, ++YP)
830 if (!isSameTemplateArg(Context, *XP, *YP))
831 return false;
832
833 return true;
834 }
835
836 return false;
837}
838
839/// \brief Helper function to build a TemplateParameter when we don't
840/// know its type statically.
841static TemplateParameter makeTemplateParameter(Decl *D) {
842 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
843 return TemplateParameter(TTP);
844 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
845 return TemplateParameter(NTTP);
846
847 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
848}
849
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000850/// \brief Perform template argument deduction to determine whether
851/// the given template arguments match the given class template
852/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +0000853Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000854Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000855 const TemplateArgumentList &TemplateArgs,
856 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000857 // C++ [temp.class.spec.match]p2:
858 // A partial specialization matches a given actual template
859 // argument list if the template arguments of the partial
860 // specialization can be deduced from the actual template argument
861 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +0000862 SFINAETrap Trap(*this);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000863 llvm::SmallVector<TemplateArgument, 4> Deduced;
864 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000865 if (TemplateDeductionResult Result
866 = ::DeduceTemplateArguments(Context,
867 Partial->getTemplateParameters(),
868 Partial->getTemplateArgs(),
869 TemplateArgs, Info, Deduced))
870 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +0000871
Douglas Gregor637a4092009-06-10 23:47:09 +0000872 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
873 Deduced.data(), Deduced.size());
874 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000875 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +0000876
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000877 // C++ [temp.deduct.type]p2:
878 // [...] or if any template argument remains neither deduced nor
879 // explicitly specified, template argument deduction fails.
Anders Carlssonfb250522009-06-23 01:26:57 +0000880 TemplateArgumentListBuilder Builder(Partial->getTemplateParameters(),
881 Deduced.size());
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000882 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000883 if (Deduced[I].isNull()) {
884 Decl *Param
885 = const_cast<Decl *>(Partial->getTemplateParameters()->getParam(I));
886 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
887 Info.Param = TTP;
888 else if (NonTypeTemplateParmDecl *NTTP
889 = dyn_cast<NonTypeTemplateParmDecl>(Param))
890 Info.Param = NTTP;
891 else
892 Info.Param = cast<TemplateTemplateParmDecl>(Param);
893 return TDK_Incomplete;
894 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000895
Anders Carlssonfb250522009-06-23 01:26:57 +0000896 Builder.Append(Deduced[I]);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000897 }
898
899 // Form the template argument list from the deduced template arguments.
900 TemplateArgumentList *DeducedArgumentList
Anders Carlssonfb250522009-06-23 01:26:57 +0000901 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000902 Info.reset(DeducedArgumentList);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000903
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000904 // Substitute the deduced template arguments into the template
905 // arguments of the class template partial specialization, and
906 // verify that the instantiated template arguments are both valid
907 // and are equivalent to the template arguments originally provided
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000908 // to the class template.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000909 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
910 const TemplateArgumentList &PartialTemplateArgs = Partial->getTemplateArgs();
911 for (unsigned I = 0, N = PartialTemplateArgs.flat_size(); I != N; ++I) {
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000912 Decl *Param = const_cast<Decl *>(
913 ClassTemplate->getTemplateParameters()->getParam(I));
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000914 TemplateArgument InstArg = Instantiate(PartialTemplateArgs[I],
915 *DeducedArgumentList);
916 if (InstArg.isNull()) {
917 Info.Param = makeTemplateParameter(Param);
918 Info.FirstArg = PartialTemplateArgs[I];
919 return TDK_SubstitutionFailure;
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000920 }
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000921
922 if (InstArg.getKind() == TemplateArgument::Expression) {
923 // When the argument is an expression, check the expression result
924 // against the actual template parameter to get down to the canonical
925 // template argument.
926 Expr *InstExpr = InstArg.getAsExpr();
927 if (NonTypeTemplateParmDecl *NTTP
928 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
929 if (CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
930 Info.Param = makeTemplateParameter(Param);
931 Info.FirstArg = PartialTemplateArgs[I];
932 return TDK_SubstitutionFailure;
933 }
934 } else if (TemplateTemplateParmDecl *TTP
935 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
936 // FIXME: template template arguments should really resolve to decls
937 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InstExpr);
938 if (!DRE || CheckTemplateArgument(TTP, DRE)) {
939 Info.Param = makeTemplateParameter(Param);
940 Info.FirstArg = PartialTemplateArgs[I];
941 return TDK_SubstitutionFailure;
942 }
943 }
944 }
945
946 if (!isSameTemplateArg(Context, TemplateArgs[I], InstArg)) {
947 Info.Param = makeTemplateParameter(Param);
948 Info.FirstArg = TemplateArgs[I];
949 Info.SecondArg = InstArg;
950 return TDK_NonDeducedMismatch;
951 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000952 }
953
Douglas Gregorbb260412009-06-14 08:02:22 +0000954 if (Trap.hasErrorOccurred())
955 return TDK_SubstitutionFailure;
956
Douglas Gregorf67875d2009-06-12 18:26:56 +0000957 return TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000958}
Douglas Gregor031a5882009-06-13 00:26:55 +0000959
Douglas Gregor41128772009-06-26 23:27:24 +0000960/// \brief Determine whether the given type T is a simple-template-id type.
961static bool isSimpleTemplateIdType(QualType T) {
962 if (const TemplateSpecializationType *Spec
963 = T->getAsTemplateSpecializationType())
964 return Spec->getTemplateName().getAsTemplateDecl() != 0;
965
966 return false;
967}
Douglas Gregor83314aa2009-07-08 20:55:45 +0000968
969/// \brief Substitute the explicitly-provided template arguments into the
970/// given function template according to C++ [temp.arg.explicit].
971///
972/// \param FunctionTemplate the function template into which the explicit
973/// template arguments will be substituted.
974///
975/// \param ExplicitTemplateArguments the explicitly-specified template
976/// arguments.
977///
978/// \param NumExplicitTemplateArguments the number of explicitly-specified
979/// template arguments in @p ExplicitTemplateArguments. This value may be zero.
980///
981/// \param Deduced the deduced template arguments, which will be populated
982/// with the converted and checked explicit template arguments.
983///
984/// \param ParamTypes will be populated with the instantiated function
985/// parameters.
986///
987/// \param FunctionType if non-NULL, the result type of the function template
988/// will also be instantiated and the pointed-to value will be updated with
989/// the instantiated function type.
990///
991/// \param Info if substitution fails for any reason, this object will be
992/// populated with more information about the failure.
993///
994/// \returns TDK_Success if substitution was successful, or some failure
995/// condition.
996Sema::TemplateDeductionResult
997Sema::SubstituteExplicitTemplateArguments(
998 FunctionTemplateDecl *FunctionTemplate,
999 const TemplateArgument *ExplicitTemplateArgs,
1000 unsigned NumExplicitTemplateArgs,
1001 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1002 llvm::SmallVectorImpl<QualType> &ParamTypes,
1003 QualType *FunctionType,
1004 TemplateDeductionInfo &Info) {
1005 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1006 TemplateParameterList *TemplateParams
1007 = FunctionTemplate->getTemplateParameters();
1008
1009 if (NumExplicitTemplateArgs == 0) {
1010 // No arguments to substitute; just copy over the parameter types and
1011 // fill in the function type.
1012 for (FunctionDecl::param_iterator P = Function->param_begin(),
1013 PEnd = Function->param_end();
1014 P != PEnd;
1015 ++P)
1016 ParamTypes.push_back((*P)->getType());
1017
1018 if (FunctionType)
1019 *FunctionType = Function->getType();
1020 return TDK_Success;
1021 }
1022
1023 // Substitution of the explicit template arguments into a function template
1024 /// is a SFINAE context. Trap any errors that might occur.
1025 SFINAETrap Trap(*this);
1026
1027 // C++ [temp.arg.explicit]p3:
1028 // Template arguments that are present shall be specified in the
1029 // declaration order of their corresponding template-parameters. The
1030 // template argument list shall not specify more template-arguments than
1031 // there are corresponding template-parameters.
1032 TemplateArgumentListBuilder Builder(TemplateParams,
1033 NumExplicitTemplateArgs);
1034
1035 // Enter a new template instantiation context where we check the
1036 // explicitly-specified template arguments against this function template,
1037 // and then substitute them into the function parameter types.
1038 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1039 FunctionTemplate, Deduced.data(), Deduced.size(),
1040 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution);
1041 if (Inst)
1042 return TDK_InstantiationDepth;
1043
1044 if (CheckTemplateArgumentList(FunctionTemplate,
1045 SourceLocation(), SourceLocation(),
1046 ExplicitTemplateArgs,
1047 NumExplicitTemplateArgs,
1048 SourceLocation(),
1049 true,
1050 Builder) || Trap.hasErrorOccurred())
1051 return TDK_InvalidExplicitArguments;
1052
1053 // Form the template argument list from the explicitly-specified
1054 // template arguments.
1055 TemplateArgumentList *ExplicitArgumentList
1056 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1057 Info.reset(ExplicitArgumentList);
1058
1059 // Instantiate the types of each of the function parameters given the
1060 // explicitly-specified template arguments.
1061 for (FunctionDecl::param_iterator P = Function->param_begin(),
1062 PEnd = Function->param_end();
1063 P != PEnd;
1064 ++P) {
1065 QualType ParamType = InstantiateType((*P)->getType(),
1066 *ExplicitArgumentList,
1067 (*P)->getLocation(),
1068 (*P)->getDeclName());
1069 if (ParamType.isNull() || Trap.hasErrorOccurred())
1070 return TDK_SubstitutionFailure;
1071
1072 ParamTypes.push_back(ParamType);
1073 }
1074
1075 // If the caller wants a full function type back, instantiate the return
1076 // type and form that function type.
1077 if (FunctionType) {
1078 // FIXME: exception-specifications?
1079 const FunctionProtoType *Proto
1080 = Function->getType()->getAsFunctionProtoType();
1081 assert(Proto && "Function template does not have a prototype?");
1082
1083 QualType ResultType = InstantiateType(Proto->getResultType(),
1084 *ExplicitArgumentList,
1085 Function->getTypeSpecStartLoc(),
1086 Function->getDeclName());
1087 if (ResultType.isNull() || Trap.hasErrorOccurred())
1088 return TDK_SubstitutionFailure;
1089
1090 *FunctionType = BuildFunctionType(ResultType,
1091 ParamTypes.data(), ParamTypes.size(),
1092 Proto->isVariadic(),
1093 Proto->getTypeQuals(),
1094 Function->getLocation(),
1095 Function->getDeclName());
1096 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1097 return TDK_SubstitutionFailure;
1098 }
1099
1100 // C++ [temp.arg.explicit]p2:
1101 // Trailing template arguments that can be deduced (14.8.2) may be
1102 // omitted from the list of explicit template-arguments. If all of the
1103 // template arguments can be deduced, they may all be omitted; in this
1104 // case, the empty template argument list <> itself may also be omitted.
1105 //
1106 // Take all of the explicitly-specified arguments and put them into the
1107 // set of deduced template arguments.
1108 Deduced.reserve(TemplateParams->size());
1109 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
1110 Deduced.push_back(ExplicitArgumentList->get(I));
1111
1112 return TDK_Success;
1113}
1114
1115/// \brief Finish template argument deduction for a function template,
1116/// checking the deduced template arguments for completeness and forming
1117/// the function template specialization.
1118Sema::TemplateDeductionResult
1119Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
1120 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1121 FunctionDecl *&Specialization,
1122 TemplateDeductionInfo &Info) {
1123 TemplateParameterList *TemplateParams
1124 = FunctionTemplate->getTemplateParameters();
1125
1126 // C++ [temp.deduct.type]p2:
1127 // [...] or if any template argument remains neither deduced nor
1128 // explicitly specified, template argument deduction fails.
1129 TemplateArgumentListBuilder Builder(TemplateParams, Deduced.size());
1130 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1131 if (Deduced[I].isNull()) {
1132 Info.Param = makeTemplateParameter(
1133 const_cast<Decl *>(TemplateParams->getParam(I)));
1134 return TDK_Incomplete;
1135 }
1136
1137 Builder.Append(Deduced[I]);
1138 }
1139
1140 // Form the template argument list from the deduced template arguments.
1141 TemplateArgumentList *DeducedArgumentList
1142 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1143 Info.reset(DeducedArgumentList);
1144
1145 // Template argument deduction for function templates in a SFINAE context.
1146 // Trap any errors that might occur.
1147 SFINAETrap Trap(*this);
1148
1149 // Enter a new template instantiation context while we instantiate the
1150 // actual function declaration.
1151 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1152 FunctionTemplate, Deduced.data(), Deduced.size(),
1153 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
1154 if (Inst)
1155 return TDK_InstantiationDepth;
1156
1157 // Substitute the deduced template arguments into the function template
1158 // declaration to produce the function template specialization.
1159 Specialization = cast_or_null<FunctionDecl>(
1160 InstantiateDecl(FunctionTemplate->getTemplatedDecl(),
1161 FunctionTemplate->getDeclContext(),
1162 *DeducedArgumentList));
1163 if (!Specialization)
1164 return TDK_SubstitutionFailure;
1165
1166 // If the template argument list is owned by the function template
1167 // specialization, release it.
1168 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList)
1169 Info.take();
1170
1171 // There may have been an error that did not prevent us from constructing a
1172 // declaration. Mark the declaration invalid and return with a substitution
1173 // failure.
1174 if (Trap.hasErrorOccurred()) {
1175 Specialization->setInvalidDecl(true);
1176 return TDK_SubstitutionFailure;
1177 }
1178
1179 return TDK_Success;
1180}
1181
Douglas Gregore53060f2009-06-25 22:08:12 +00001182/// \brief Perform template argument deduction from a function call
1183/// (C++ [temp.deduct.call]).
1184///
1185/// \param FunctionTemplate the function template for which we are performing
1186/// template argument deduction.
1187///
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001188/// \param HasExplicitTemplateArgs whether any template arguments were
1189/// explicitly specified.
1190///
1191/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1192/// the explicitly-specified template arguments.
1193///
1194/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1195/// the number of explicitly-specified template arguments in
1196/// @p ExplicitTemplateArguments. This value may be zero.
1197///
Douglas Gregore53060f2009-06-25 22:08:12 +00001198/// \param Args the function call arguments
1199///
1200/// \param NumArgs the number of arguments in Args
1201///
1202/// \param Specialization if template argument deduction was successful,
1203/// this will be set to the function template specialization produced by
1204/// template argument deduction.
1205///
1206/// \param Info the argument will be updated to provide additional information
1207/// about template argument deduction.
1208///
1209/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001210Sema::TemplateDeductionResult
1211Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001212 bool HasExplicitTemplateArgs,
1213 const TemplateArgument *ExplicitTemplateArgs,
1214 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001215 Expr **Args, unsigned NumArgs,
1216 FunctionDecl *&Specialization,
1217 TemplateDeductionInfo &Info) {
1218 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001219
Douglas Gregore53060f2009-06-25 22:08:12 +00001220 // C++ [temp.deduct.call]p1:
1221 // Template argument deduction is done by comparing each function template
1222 // parameter type (call it P) with the type of the corresponding argument
1223 // of the call (call it A) as described below.
1224 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001225 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001226 return TDK_TooFewArguments;
1227 else if (NumArgs > Function->getNumParams()) {
1228 const FunctionProtoType *Proto
1229 = Function->getType()->getAsFunctionProtoType();
1230 if (!Proto->isVariadic())
1231 return TDK_TooManyArguments;
1232
1233 CheckArgs = Function->getNumParams();
1234 }
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001235
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001236 // The types of the parameters from which we will perform template argument
1237 // deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001238 TemplateParameterList *TemplateParams
1239 = FunctionTemplate->getTemplateParameters();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001240 llvm::SmallVector<TemplateArgument, 4> Deduced;
1241 llvm::SmallVector<QualType, 4> ParamTypes;
1242 if (NumExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001243 TemplateDeductionResult Result =
1244 SubstituteExplicitTemplateArguments(FunctionTemplate,
1245 ExplicitTemplateArgs,
1246 NumExplicitTemplateArgs,
1247 Deduced,
1248 ParamTypes,
1249 0,
1250 Info);
1251 if (Result)
1252 return Result;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001253 } else {
1254 // Just fill in the parameter types from the function declaration.
1255 for (unsigned I = 0; I != CheckArgs; ++I)
1256 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1257 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00001258
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001259 // Deduce template arguments from the function parameters.
1260 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001261 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001262 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001263 QualType ArgType = Args[I]->getType();
Douglas Gregor500d3312009-06-26 18:27:22 +00001264
Douglas Gregore53060f2009-06-25 22:08:12 +00001265 // C++ [temp.deduct.call]p2:
1266 // If P is not a reference type:
1267 QualType CanonParamType = Context.getCanonicalType(ParamType);
Douglas Gregor500d3312009-06-26 18:27:22 +00001268 bool ParamWasReference = isa<ReferenceType>(CanonParamType);
1269 if (!ParamWasReference) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001270 // - If A is an array type, the pointer type produced by the
1271 // array-to-pointer standard conversion (4.2) is used in place of
1272 // A for type deduction; otherwise,
1273 if (ArgType->isArrayType())
1274 ArgType = Context.getArrayDecayedType(ArgType);
1275 // - If A is a function type, the pointer type produced by the
1276 // function-to-pointer standard conversion (4.3) is used in place
1277 // of A for type deduction; otherwise,
1278 else if (ArgType->isFunctionType())
1279 ArgType = Context.getPointerType(ArgType);
1280 else {
1281 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1282 // type are ignored for type deduction.
1283 QualType CanonArgType = Context.getCanonicalType(ArgType);
1284 if (CanonArgType.getCVRQualifiers())
1285 ArgType = CanonArgType.getUnqualifiedType();
1286 }
1287 }
1288
1289 // C++0x [temp.deduct.call]p3:
1290 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1291 // are ignored for type deduction.
1292 if (CanonParamType.getCVRQualifiers())
1293 ParamType = CanonParamType.getUnqualifiedType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001294 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001295 // [...] If P is a reference type, the type referred to by P is used
1296 // for type deduction.
1297 ParamType = ParamRefType->getPointeeType();
1298
1299 // [...] If P is of the form T&&, where T is a template parameter, and
1300 // the argument is an lvalue, the type A& is used in place of A for
1301 // type deduction.
1302 if (isa<RValueReferenceType>(ParamRefType) &&
1303 ParamRefType->getAsTemplateTypeParmType() &&
1304 Args[I]->isLvalue(Context) == Expr::LV_Valid)
1305 ArgType = Context.getLValueReferenceType(ArgType);
1306 }
1307
1308 // C++0x [temp.deduct.call]p4:
1309 // In general, the deduction process attempts to find template argument
1310 // values that will make the deduced A identical to A (after the type A
1311 // is transformed as described above). [...]
Douglas Gregor508f1c82009-06-26 23:10:12 +00001312 unsigned TDF = 0;
1313
1314 // - If the original P is a reference type, the deduced A (i.e., the
1315 // type referred to by the reference) can be more cv-qualified than
1316 // the transformed A.
1317 if (ParamWasReference)
1318 TDF |= TDF_ParamWithReferenceType;
1319 // - The transformed A can be another pointer or pointer to member
1320 // type that can be converted to the deduced A via a qualification
1321 // conversion (4.4).
1322 if (ArgType->isPointerType() || ArgType->isMemberPointerType())
1323 TDF |= TDF_IgnoreQualifiers;
Douglas Gregor41128772009-06-26 23:27:24 +00001324 // - If P is a class and P has the form simple-template-id, then the
1325 // transformed A can be a derived class of the deduced A. Likewise,
1326 // if P is a pointer to a class of the form simple-template-id, the
1327 // transformed A can be a pointer to a derived class pointed to by
1328 // the deduced A.
1329 if (isSimpleTemplateIdType(ParamType) ||
1330 (isa<PointerType>(ParamType) &&
1331 isSimpleTemplateIdType(
Ted Kremenek35366a62009-07-17 17:50:17 +00001332 ParamType->getAsPointerType()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00001333 TDF |= TDF_DerivedClass;
1334
Douglas Gregore53060f2009-06-25 22:08:12 +00001335 if (TemplateDeductionResult Result
1336 = ::DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00001337 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001338 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00001339 return Result;
1340
Douglas Gregor8fdc3c42009-07-07 23:12:18 +00001341 // FIXME: C++0x [temp.deduct.call] paragraphs 6-9 deal with function
Douglas Gregore53060f2009-06-25 22:08:12 +00001342 // pointer parameters.
1343 }
Douglas Gregore53060f2009-06-25 22:08:12 +00001344
Douglas Gregor83314aa2009-07-08 20:55:45 +00001345 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1346 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00001347}
1348
Douglas Gregor83314aa2009-07-08 20:55:45 +00001349/// \brief Deduce template arguments when taking the address of a function
1350/// template (C++ [temp.deduct.funcaddr]).
1351///
1352/// \param FunctionTemplate the function template for which we are performing
1353/// template argument deduction.
1354///
1355/// \param HasExplicitTemplateArgs whether any template arguments were
1356/// explicitly specified.
1357///
1358/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1359/// the explicitly-specified template arguments.
1360///
1361/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1362/// the number of explicitly-specified template arguments in
1363/// @p ExplicitTemplateArguments. This value may be zero.
1364///
1365/// \param ArgFunctionType the function type that will be used as the
1366/// "argument" type (A) when performing template argument deduction from the
1367/// function template's function type.
1368///
1369/// \param Specialization if template argument deduction was successful,
1370/// this will be set to the function template specialization produced by
1371/// template argument deduction.
1372///
1373/// \param Info the argument will be updated to provide additional information
1374/// about template argument deduction.
1375///
1376/// \returns the result of template argument deduction.
1377Sema::TemplateDeductionResult
1378Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1379 bool HasExplicitTemplateArgs,
1380 const TemplateArgument *ExplicitTemplateArgs,
1381 unsigned NumExplicitTemplateArgs,
1382 QualType ArgFunctionType,
1383 FunctionDecl *&Specialization,
1384 TemplateDeductionInfo &Info) {
1385 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1386 TemplateParameterList *TemplateParams
1387 = FunctionTemplate->getTemplateParameters();
1388 QualType FunctionType = Function->getType();
1389
1390 // Substitute any explicit template arguments.
1391 llvm::SmallVector<TemplateArgument, 4> Deduced;
1392 llvm::SmallVector<QualType, 4> ParamTypes;
1393 if (HasExplicitTemplateArgs) {
1394 if (TemplateDeductionResult Result
1395 = SubstituteExplicitTemplateArguments(FunctionTemplate,
1396 ExplicitTemplateArgs,
1397 NumExplicitTemplateArgs,
1398 Deduced, ParamTypes,
1399 &FunctionType, Info))
1400 return Result;
1401 }
1402
1403 // Template argument deduction for function templates in a SFINAE context.
1404 // Trap any errors that might occur.
1405 SFINAETrap Trap(*this);
1406
1407 // Deduce template arguments from the function type.
1408 Deduced.resize(TemplateParams->size());
1409 if (TemplateDeductionResult Result
1410 = ::DeduceTemplateArguments(Context, TemplateParams,
1411 FunctionType, ArgFunctionType, Info,
1412 Deduced, 0))
1413 return Result;
1414
1415 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1416 Specialization, Info);
1417}
1418
1419
Douglas Gregor031a5882009-06-13 00:26:55 +00001420static void
1421MarkDeducedTemplateParameters(Sema &SemaRef,
1422 const TemplateArgument &TemplateArg,
1423 llvm::SmallVectorImpl<bool> &Deduced);
1424
1425/// \brief Mark the template arguments that are deduced by the given
1426/// expression.
1427static void
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001428MarkDeducedTemplateParameters(const Expr *E,
1429 llvm::SmallVectorImpl<bool> &Deduced) {
1430 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor031a5882009-06-13 00:26:55 +00001431 if (!E)
1432 return;
1433
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001434 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00001435 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
1436 if (!NTTP)
1437 return;
1438
1439 Deduced[NTTP->getIndex()] = true;
1440}
1441
1442/// \brief Mark the template parameters that are deduced by the given
1443/// type.
1444static void
1445MarkDeducedTemplateParameters(Sema &SemaRef, QualType T,
1446 llvm::SmallVectorImpl<bool> &Deduced) {
1447 // Non-dependent types have nothing deducible
1448 if (!T->isDependentType())
1449 return;
1450
1451 T = SemaRef.Context.getCanonicalType(T);
1452 switch (T->getTypeClass()) {
1453 case Type::ExtQual:
1454 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001455 QualType(cast<ExtQualType>(T)->getBaseType(), 0),
Douglas Gregor031a5882009-06-13 00:26:55 +00001456 Deduced);
1457 break;
1458
1459 case Type::Pointer:
1460 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001461 cast<PointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001462 Deduced);
1463 break;
1464
1465 case Type::BlockPointer:
1466 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001467 cast<BlockPointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001468 Deduced);
1469 break;
1470
1471 case Type::LValueReference:
1472 case Type::RValueReference:
1473 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001474 cast<ReferenceType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001475 Deduced);
1476 break;
1477
1478 case Type::MemberPointer: {
1479 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
1480 MarkDeducedTemplateParameters(SemaRef, MemPtr->getPointeeType(), Deduced);
1481 MarkDeducedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
1482 Deduced);
1483 break;
1484 }
1485
1486 case Type::DependentSizedArray:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001487 MarkDeducedTemplateParameters(cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001488 Deduced);
1489 // Fall through to check the element type
1490
1491 case Type::ConstantArray:
1492 case Type::IncompleteArray:
1493 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001494 cast<ArrayType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001495 Deduced);
1496 break;
1497
1498 case Type::Vector:
1499 case Type::ExtVector:
1500 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001501 cast<VectorType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001502 Deduced);
1503 break;
1504
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001505 case Type::DependentSizedExtVector: {
1506 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001507 = cast<DependentSizedExtVectorType>(T);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001508 MarkDeducedTemplateParameters(SemaRef, VecType->getElementType(), Deduced);
1509 MarkDeducedTemplateParameters(VecType->getSizeExpr(), Deduced);
1510 break;
1511 }
1512
Douglas Gregor031a5882009-06-13 00:26:55 +00001513 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001514 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001515 MarkDeducedTemplateParameters(SemaRef, Proto->getResultType(), Deduced);
1516 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
1517 MarkDeducedTemplateParameters(SemaRef, Proto->getArgType(I), Deduced);
1518 break;
1519 }
1520
1521 case Type::TemplateTypeParm:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001522 Deduced[cast<TemplateTypeParmType>(T)->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00001523 break;
1524
1525 case Type::TemplateSpecialization: {
1526 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001527 = cast<TemplateSpecializationType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001528 if (TemplateDecl *Template = Spec->getTemplateName().getAsTemplateDecl())
1529 if (TemplateTemplateParmDecl *TTP
1530 = dyn_cast<TemplateTemplateParmDecl>(Template))
1531 Deduced[TTP->getIndex()] = true;
1532
1533 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
1534 MarkDeducedTemplateParameters(SemaRef, Spec->getArg(I), Deduced);
1535
1536 break;
1537 }
1538
1539 // None of these types have any deducible parts.
1540 case Type::Builtin:
1541 case Type::FixedWidthInt:
1542 case Type::Complex:
1543 case Type::VariableArray:
1544 case Type::FunctionNoProto:
1545 case Type::Record:
1546 case Type::Enum:
1547 case Type::Typename:
1548 case Type::ObjCInterface:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001549 case Type::ObjCObjectPointer:
Douglas Gregor031a5882009-06-13 00:26:55 +00001550#define TYPE(Class, Base)
1551#define ABSTRACT_TYPE(Class, Base)
1552#define DEPENDENT_TYPE(Class, Base)
1553#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1554#include "clang/AST/TypeNodes.def"
1555 break;
1556 }
1557}
1558
1559/// \brief Mark the template parameters that are deduced by this
1560/// template argument.
1561static void
1562MarkDeducedTemplateParameters(Sema &SemaRef,
1563 const TemplateArgument &TemplateArg,
1564 llvm::SmallVectorImpl<bool> &Deduced) {
1565 switch (TemplateArg.getKind()) {
1566 case TemplateArgument::Null:
1567 case TemplateArgument::Integral:
1568 break;
1569
1570 case TemplateArgument::Type:
1571 MarkDeducedTemplateParameters(SemaRef, TemplateArg.getAsType(), Deduced);
1572 break;
1573
1574 case TemplateArgument::Declaration:
1575 if (TemplateTemplateParmDecl *TTP
1576 = dyn_cast<TemplateTemplateParmDecl>(TemplateArg.getAsDecl()))
1577 Deduced[TTP->getIndex()] = true;
1578 break;
1579
1580 case TemplateArgument::Expression:
1581 MarkDeducedTemplateParameters(TemplateArg.getAsExpr(), Deduced);
1582 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001583 case TemplateArgument::Pack:
1584 assert(0 && "FIXME: Implement!");
1585 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00001586 }
1587}
1588
1589/// \brief Mark the template parameters can be deduced by the given
1590/// template argument list.
1591///
1592/// \param TemplateArgs the template argument list from which template
1593/// parameters will be deduced.
1594///
1595/// \param Deduced a bit vector whose elements will be set to \c true
1596/// to indicate when the corresponding template parameter will be
1597/// deduced.
1598void
1599Sema::MarkDeducedTemplateParameters(const TemplateArgumentList &TemplateArgs,
1600 llvm::SmallVectorImpl<bool> &Deduced) {
1601 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1602 ::MarkDeducedTemplateParameters(*this, TemplateArgs[I], Deduced);
1603}