blob: 4e6d0f4dd167b33de20c19ea3eee84f770de3023 [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();
364 QualType DeducedType = Arg.getQualifiedType(Quals);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000365
366 if (Deduced[Index].isNull())
367 Deduced[Index] = TemplateArgument(SourceLocation(), DeducedType);
368 else {
369 // C++ [temp.deduct.type]p2:
370 // [...] If type deduction cannot be done for any P/A pair, or if for
371 // any pair the deduction leads to more than one possible set of
372 // deduced values, or if different pairs yield different deduced
373 // values, or if any template argument remains neither deduced nor
374 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000375 if (Deduced[Index].getAsType() != DeducedType) {
376 Info.Param
377 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
378 Info.FirstArg = Deduced[Index];
379 Info.SecondArg = TemplateArgument(SourceLocation(), Arg);
380 return Sema::TDK_Inconsistent;
381 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000382 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000383 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000384 }
385
Douglas Gregorf67875d2009-06-12 18:26:56 +0000386 // Set up the template argument deduction information for a failure.
387 Info.FirstArg = TemplateArgument(SourceLocation(), ParamIn);
388 Info.SecondArg = TemplateArgument(SourceLocation(), ArgIn);
389
Douglas Gregor508f1c82009-06-26 23:10:12 +0000390 // Check the cv-qualifiers on the parameter and argument types.
391 if (!(TDF & TDF_IgnoreQualifiers)) {
392 if (TDF & TDF_ParamWithReferenceType) {
393 if (Param.isMoreQualifiedThan(Arg))
394 return Sema::TDK_NonDeducedMismatch;
395 } else {
396 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
397 return Sema::TDK_NonDeducedMismatch;
398 }
399 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000400
Douglas Gregord560d502009-06-04 00:21:18 +0000401 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000402 // No deduction possible for these types
403 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000404 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000405
406 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000407 case Type::Pointer: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000408 const PointerType *PointerArg = Arg->getAsPointerType();
Douglas Gregord560d502009-06-04 00:21:18 +0000409 if (!PointerArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000410 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000411
Douglas Gregor41128772009-06-26 23:27:24 +0000412 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000413 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000414 cast<PointerType>(Param)->getPointeeType(),
415 PointerArg->getPointeeType(),
Douglas Gregor41128772009-06-26 23:27:24 +0000416 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000417 }
418
Douglas Gregor199d9912009-06-05 00:53:49 +0000419 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000420 case Type::LValueReference: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000421 const LValueReferenceType *ReferenceArg = Arg->getAsLValueReferenceType();
Douglas Gregord560d502009-06-04 00:21:18 +0000422 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000423 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000424
Douglas Gregorf67875d2009-06-12 18:26:56 +0000425 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000426 cast<LValueReferenceType>(Param)->getPointeeType(),
427 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000428 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000429 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000430
Douglas Gregor199d9912009-06-05 00:53:49 +0000431 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000432 case Type::RValueReference: {
Ted Kremenek35366a62009-07-17 17:50:17 +0000433 const RValueReferenceType *ReferenceArg = Arg->getAsRValueReferenceType();
Douglas Gregord560d502009-06-04 00:21:18 +0000434 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000435 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord560d502009-06-04 00:21:18 +0000436
Douglas Gregorf67875d2009-06-12 18:26:56 +0000437 return DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000438 cast<RValueReferenceType>(Param)->getPointeeType(),
439 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000440 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000441 }
442
Douglas Gregor199d9912009-06-05 00:53:49 +0000443 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000444 case Type::IncompleteArray: {
445 const IncompleteArrayType *IncompleteArrayArg =
446 Context.getAsIncompleteArrayType(Arg);
447 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000448 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000449
Douglas Gregorf67875d2009-06-12 18:26:56 +0000450 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000451 Context.getAsIncompleteArrayType(Param)->getElementType(),
452 IncompleteArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000453 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000454 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000455
456 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000457 case Type::ConstantArray: {
458 const ConstantArrayType *ConstantArrayArg =
459 Context.getAsConstantArrayType(Arg);
460 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000461 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000462
463 const ConstantArrayType *ConstantArrayParm =
464 Context.getAsConstantArrayType(Param);
465 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000466 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000467
Douglas Gregorf67875d2009-06-12 18:26:56 +0000468 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000469 ConstantArrayParm->getElementType(),
470 ConstantArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000471 Info, Deduced, 0);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000472 }
473
Douglas Gregor199d9912009-06-05 00:53:49 +0000474 // type [i]
475 case Type::DependentSizedArray: {
476 const ArrayType *ArrayArg = dyn_cast<ArrayType>(Arg);
477 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000478 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000479
480 // Check the element type of the arrays
481 const DependentSizedArrayType *DependentArrayParm
482 = cast<DependentSizedArrayType>(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000483 if (Sema::TemplateDeductionResult Result
484 = DeduceTemplateArguments(Context, TemplateParams,
485 DependentArrayParm->getElementType(),
486 ArrayArg->getElementType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000487 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000488 return Result;
Douglas Gregor199d9912009-06-05 00:53:49 +0000489
490 // Determine the array bound is something we can deduce.
491 NonTypeTemplateParmDecl *NTTP
492 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
493 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000494 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000495
496 // We can perform template argument deduction for the given non-type
497 // template parameter.
498 assert(NTTP->getDepth() == 0 &&
499 "Cannot deduce non-type template argument at depth > 0");
500 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000501 = dyn_cast<ConstantArrayType>(ArrayArg)) {
502 llvm::APSInt Size(ConstantArrayArg->getSize());
503 return DeduceNonTypeTemplateArgument(Context, NTTP, Size,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000504 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000505 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000506 if (const DependentSizedArrayType *DependentArrayArg
507 = dyn_cast<DependentSizedArrayType>(ArrayArg))
508 return DeduceNonTypeTemplateArgument(Context, NTTP,
509 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000510 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000511
512 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000513 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000514 }
515
Douglas Gregor0fce0ae2009-06-08 15:59:14 +0000516 // type(*)(T)
517 // T(*)()
518 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000519 case Type::FunctionProto: {
520 const FunctionProtoType *FunctionProtoArg =
521 dyn_cast<FunctionProtoType>(Arg);
522 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000523 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000524
525 const FunctionProtoType *FunctionProtoParam =
526 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000527
528 if (FunctionProtoParam->getTypeQuals() !=
529 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000530 return Sema::TDK_NonDeducedMismatch;
Anders Carlssona27fad52009-06-08 15:19:08 +0000531
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000532 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000533 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000534
535 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000536 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000537
Anders Carlssona27fad52009-06-08 15:19:08 +0000538 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000539 if (Sema::TemplateDeductionResult Result
540 = DeduceTemplateArguments(Context, TemplateParams,
541 FunctionProtoParam->getResultType(),
542 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000543 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000544 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000545
Anders Carlssona27fad52009-06-08 15:19:08 +0000546 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
547 // Check argument types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000548 if (Sema::TemplateDeductionResult Result
549 = DeduceTemplateArguments(Context, TemplateParams,
550 FunctionProtoParam->getArgType(I),
551 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000552 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000553 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000554 }
555
Douglas Gregorf67875d2009-06-12 18:26:56 +0000556 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000557 }
Douglas Gregord708c722009-06-09 16:35:58 +0000558
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000559 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000560 // template-name<i>
561 // TT<T> (TODO)
562 // TT<i> (TODO)
563 // TT<> (TODO)
564 case Type::TemplateSpecialization: {
565 const TemplateSpecializationType *SpecParam
566 = cast<TemplateSpecializationType>(Param);
Anders Carlssona27fad52009-06-08 15:19:08 +0000567
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000568 // Try to deduce template arguments from the template-id.
569 Sema::TemplateDeductionResult Result
570 = DeduceTemplateArguments(Context, TemplateParams, SpecParam, Arg,
571 Info, Deduced);
572
573 if (Result && (TDF & TDF_DerivedClass) &&
574 Result != Sema::TDK_Inconsistent) {
575 // C++ [temp.deduct.call]p3b3:
576 // If P is a class, and P has the form template-id, then A can be a
577 // derived class of the deduced A. Likewise, if P is a pointer to a
578 // class of the form template-id, A can be a pointer to a derived
579 // class pointed to by the deduced A.
580 //
581 // More importantly:
582 // These alternatives are considered only if type deduction would
583 // otherwise fail.
584 if (const RecordType *RecordT = dyn_cast<RecordType>(Arg)) {
585 // Use data recursion to crawl through the list of base classes.
586 // Visited contains the set of nodes we have already visited, while
587 // ToVisit is our stack of records that we still need to visit.
588 llvm::SmallPtrSet<const RecordType *, 8> Visited;
589 llvm::SmallVector<const RecordType *, 8> ToVisit;
590 ToVisit.push_back(RecordT);
591 bool Successful = false;
592 while (!ToVisit.empty()) {
593 // Retrieve the next class in the inheritance hierarchy.
594 const RecordType *NextT = ToVisit.back();
595 ToVisit.pop_back();
596
597 // If we have already seen this type, skip it.
598 if (!Visited.insert(NextT))
599 continue;
600
601 // If this is a base class, try to perform template argument
602 // deduction from it.
603 if (NextT != RecordT) {
604 Sema::TemplateDeductionResult BaseResult
605 = DeduceTemplateArguments(Context, TemplateParams, SpecParam,
606 QualType(NextT, 0), Info, Deduced);
607
608 // If template argument deduction for this base was successful,
609 // note that we had some success.
610 if (BaseResult == Sema::TDK_Success)
611 Successful = true;
612 // If deduction against this base resulted in an inconsistent
613 // set of deduced template arguments, template argument
614 // deduction fails.
615 else if (BaseResult == Sema::TDK_Inconsistent)
616 return BaseResult;
617 }
618
619 // Visit base classes
620 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
621 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
622 BaseEnd = Next->bases_end();
623 Base != BaseEnd; ++Base) {
624 assert(Base->getType()->isRecordType() &&
625 "Base class that isn't a record?");
Ted Kremenek35366a62009-07-17 17:50:17 +0000626 ToVisit.push_back(Base->getType()->getAsRecordType());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000627 }
628 }
629
630 if (Successful)
631 return Sema::TDK_Success;
632 }
633
634 }
635
636 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000637 }
638
Douglas Gregor637a4092009-06-10 23:47:09 +0000639 // T type::*
640 // T T::*
641 // T (type::*)()
642 // type (T::*)()
643 // type (type::*)(T)
644 // type (T::*)(T)
645 // T (type::*)(T)
646 // T (T::*)()
647 // T (T::*)(T)
648 case Type::MemberPointer: {
649 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
650 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
651 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000652 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000653
Douglas Gregorf67875d2009-06-12 18:26:56 +0000654 if (Sema::TemplateDeductionResult Result
655 = DeduceTemplateArguments(Context, TemplateParams,
656 MemPtrParam->getPointeeType(),
657 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000658 Info, Deduced,
659 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000660 return Result;
661
662 return DeduceTemplateArguments(Context, TemplateParams,
663 QualType(MemPtrParam->getClass(), 0),
664 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000665 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000666 }
667
Anders Carlsson9a917e42009-06-12 22:56:54 +0000668 // (clang extension)
669 //
Anders Carlsson859ba502009-06-12 16:23:10 +0000670 // type(^)(T)
671 // T(^)()
672 // T(^)(T)
673 case Type::BlockPointer: {
674 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
675 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
676
677 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000678 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson859ba502009-06-12 16:23:10 +0000679
Douglas Gregorf67875d2009-06-12 18:26:56 +0000680 return DeduceTemplateArguments(Context, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000681 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000682 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000683 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000684 }
685
Douglas Gregor637a4092009-06-10 23:47:09 +0000686 case Type::TypeOfExpr:
687 case Type::TypeOf:
688 case Type::Typename:
689 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000690 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000691
Douglas Gregord560d502009-06-04 00:21:18 +0000692 default:
693 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000694 }
695
696 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000697 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000698}
699
Douglas Gregorf67875d2009-06-12 18:26:56 +0000700static Sema::TemplateDeductionResult
701DeduceTemplateArguments(ASTContext &Context,
702 TemplateParameterList *TemplateParams,
703 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000704 const TemplateArgument &Arg,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000705 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000706 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000707 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000708 case TemplateArgument::Null:
709 assert(false && "Null template argument in parameter list");
710 break;
711
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000712 case TemplateArgument::Type:
Douglas Gregor199d9912009-06-05 00:53:49 +0000713 assert(Arg.getKind() == TemplateArgument::Type && "Type/value mismatch");
Douglas Gregor508f1c82009-06-26 23:10:12 +0000714 return DeduceTemplateArguments(Context, TemplateParams, Param.getAsType(),
715 Arg.getAsType(), Info, Deduced, 0);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000716
Douglas Gregor199d9912009-06-05 00:53:49 +0000717 case TemplateArgument::Declaration:
718 // FIXME: Implement this check
719 assert(false && "Unimplemented template argument deduction case");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000720 Info.FirstArg = Param;
721 Info.SecondArg = Arg;
722 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000723
724 case TemplateArgument::Integral:
725 if (Arg.getKind() == TemplateArgument::Integral) {
726 // FIXME: Zero extension + sign checking here?
Douglas Gregorf67875d2009-06-12 18:26:56 +0000727 if (*Param.getAsIntegral() == *Arg.getAsIntegral())
728 return Sema::TDK_Success;
729
730 Info.FirstArg = Param;
731 Info.SecondArg = Arg;
732 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000733 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000734
735 if (Arg.getKind() == TemplateArgument::Expression) {
736 Info.FirstArg = Param;
737 Info.SecondArg = Arg;
738 return Sema::TDK_NonDeducedMismatch;
739 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000740
741 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000742 Info.FirstArg = Param;
743 Info.SecondArg = Arg;
744 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000745
746 case TemplateArgument::Expression: {
747 if (NonTypeTemplateParmDecl *NTTP
748 = getDeducedParameterFromExpr(Param.getAsExpr())) {
749 if (Arg.getKind() == TemplateArgument::Integral)
750 // FIXME: Sign problems here
751 return DeduceNonTypeTemplateArgument(Context, NTTP,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000752 *Arg.getAsIntegral(),
753 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000754 if (Arg.getKind() == TemplateArgument::Expression)
755 return DeduceNonTypeTemplateArgument(Context, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000756 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000757
758 assert(false && "Type/value mismatch");
Douglas Gregorf67875d2009-06-12 18:26:56 +0000759 Info.FirstArg = Param;
760 Info.SecondArg = Arg;
761 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000762 }
763
764 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000765 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000766 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000767 case TemplateArgument::Pack:
768 assert(0 && "FIXME: Implement!");
769 break;
Douglas Gregor199d9912009-06-05 00:53:49 +0000770 }
771
Douglas Gregorf67875d2009-06-12 18:26:56 +0000772 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000773}
774
Douglas Gregorf67875d2009-06-12 18:26:56 +0000775static Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000776DeduceTemplateArguments(ASTContext &Context,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000777 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000778 const TemplateArgumentList &ParamList,
779 const TemplateArgumentList &ArgList,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000780 Sema::TemplateDeductionInfo &Info,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000781 llvm::SmallVectorImpl<TemplateArgument> &Deduced) {
782 assert(ParamList.size() == ArgList.size());
783 for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000784 if (Sema::TemplateDeductionResult Result
785 = DeduceTemplateArguments(Context, TemplateParams,
786 ParamList[I], ArgList[I],
787 Info, Deduced))
788 return Result;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000789 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000790 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000791}
792
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000793/// \brief Determine whether two template arguments are the same.
794static bool isSameTemplateArg(ASTContext &Context,
795 const TemplateArgument &X,
796 const TemplateArgument &Y) {
797 if (X.getKind() != Y.getKind())
798 return false;
799
800 switch (X.getKind()) {
801 case TemplateArgument::Null:
802 assert(false && "Comparing NULL template argument");
803 break;
804
805 case TemplateArgument::Type:
806 return Context.getCanonicalType(X.getAsType()) ==
807 Context.getCanonicalType(Y.getAsType());
808
809 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000810 return X.getAsDecl()->getCanonicalDecl() ==
811 Y.getAsDecl()->getCanonicalDecl();
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000812
813 case TemplateArgument::Integral:
814 return *X.getAsIntegral() == *Y.getAsIntegral();
815
816 case TemplateArgument::Expression:
817 // FIXME: We assume that all expressions are distinct, but we should
818 // really check their canonical forms.
819 return false;
820
821 case TemplateArgument::Pack:
822 if (X.pack_size() != Y.pack_size())
823 return false;
824
825 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
826 XPEnd = X.pack_end(),
827 YP = Y.pack_begin();
828 XP != XPEnd; ++XP, ++YP)
829 if (!isSameTemplateArg(Context, *XP, *YP))
830 return false;
831
832 return true;
833 }
834
835 return false;
836}
837
838/// \brief Helper function to build a TemplateParameter when we don't
839/// know its type statically.
840static TemplateParameter makeTemplateParameter(Decl *D) {
841 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
842 return TemplateParameter(TTP);
843 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
844 return TemplateParameter(NTTP);
845
846 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
847}
848
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000849/// \brief Perform template argument deduction to determine whether
850/// the given template arguments match the given class template
851/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +0000852Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000853Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000854 const TemplateArgumentList &TemplateArgs,
855 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +0000856 // C++ [temp.class.spec.match]p2:
857 // A partial specialization matches a given actual template
858 // argument list if the template arguments of the partial
859 // specialization can be deduced from the actual template argument
860 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +0000861 SFINAETrap Trap(*this);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000862 llvm::SmallVector<TemplateArgument, 4> Deduced;
863 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +0000864 if (TemplateDeductionResult Result
865 = ::DeduceTemplateArguments(Context,
866 Partial->getTemplateParameters(),
867 Partial->getTemplateArgs(),
868 TemplateArgs, Info, Deduced))
869 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +0000870
Douglas Gregor637a4092009-06-10 23:47:09 +0000871 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
872 Deduced.data(), Deduced.size());
873 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000874 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +0000875
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000876 // C++ [temp.deduct.type]p2:
877 // [...] or if any template argument remains neither deduced nor
878 // explicitly specified, template argument deduction fails.
Anders Carlssonfb250522009-06-23 01:26:57 +0000879 TemplateArgumentListBuilder Builder(Partial->getTemplateParameters(),
880 Deduced.size());
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000881 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000882 if (Deduced[I].isNull()) {
883 Decl *Param
884 = const_cast<Decl *>(Partial->getTemplateParameters()->getParam(I));
885 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
886 Info.Param = TTP;
887 else if (NonTypeTemplateParmDecl *NTTP
888 = dyn_cast<NonTypeTemplateParmDecl>(Param))
889 Info.Param = NTTP;
890 else
891 Info.Param = cast<TemplateTemplateParmDecl>(Param);
892 return TDK_Incomplete;
893 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000894
Anders Carlssonfb250522009-06-23 01:26:57 +0000895 Builder.Append(Deduced[I]);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000896 }
897
898 // Form the template argument list from the deduced template arguments.
899 TemplateArgumentList *DeducedArgumentList
Anders Carlssonfb250522009-06-23 01:26:57 +0000900 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000901 Info.reset(DeducedArgumentList);
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000902
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000903 // Substitute the deduced template arguments into the template
904 // arguments of the class template partial specialization, and
905 // verify that the instantiated template arguments are both valid
906 // and are equivalent to the template arguments originally provided
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000907 // to the class template.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000908 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
909 const TemplateArgumentList &PartialTemplateArgs = Partial->getTemplateArgs();
910 for (unsigned I = 0, N = PartialTemplateArgs.flat_size(); I != N; ++I) {
Douglas Gregorc9e5d252009-06-13 00:59:32 +0000911 Decl *Param = const_cast<Decl *>(
912 ClassTemplate->getTemplateParameters()->getParam(I));
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000913 TemplateArgument InstArg = Instantiate(PartialTemplateArgs[I],
914 *DeducedArgumentList);
915 if (InstArg.isNull()) {
916 Info.Param = makeTemplateParameter(Param);
917 Info.FirstArg = PartialTemplateArgs[I];
918 return TDK_SubstitutionFailure;
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000919 }
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000920
921 if (InstArg.getKind() == TemplateArgument::Expression) {
922 // When the argument is an expression, check the expression result
923 // against the actual template parameter to get down to the canonical
924 // template argument.
925 Expr *InstExpr = InstArg.getAsExpr();
926 if (NonTypeTemplateParmDecl *NTTP
927 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
928 if (CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
929 Info.Param = makeTemplateParameter(Param);
930 Info.FirstArg = PartialTemplateArgs[I];
931 return TDK_SubstitutionFailure;
932 }
933 } else if (TemplateTemplateParmDecl *TTP
934 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
935 // FIXME: template template arguments should really resolve to decls
936 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InstExpr);
937 if (!DRE || CheckTemplateArgument(TTP, DRE)) {
938 Info.Param = makeTemplateParameter(Param);
939 Info.FirstArg = PartialTemplateArgs[I];
940 return TDK_SubstitutionFailure;
941 }
942 }
943 }
944
945 if (!isSameTemplateArg(Context, TemplateArgs[I], InstArg)) {
946 Info.Param = makeTemplateParameter(Param);
947 Info.FirstArg = TemplateArgs[I];
948 Info.SecondArg = InstArg;
949 return TDK_NonDeducedMismatch;
950 }
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000951 }
952
Douglas Gregorbb260412009-06-14 08:02:22 +0000953 if (Trap.hasErrorOccurred())
954 return TDK_SubstitutionFailure;
955
Douglas Gregorf67875d2009-06-12 18:26:56 +0000956 return TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000957}
Douglas Gregor031a5882009-06-13 00:26:55 +0000958
Douglas Gregor41128772009-06-26 23:27:24 +0000959/// \brief Determine whether the given type T is a simple-template-id type.
960static bool isSimpleTemplateIdType(QualType T) {
961 if (const TemplateSpecializationType *Spec
962 = T->getAsTemplateSpecializationType())
963 return Spec->getTemplateName().getAsTemplateDecl() != 0;
964
965 return false;
966}
Douglas Gregor83314aa2009-07-08 20:55:45 +0000967
968/// \brief Substitute the explicitly-provided template arguments into the
969/// given function template according to C++ [temp.arg.explicit].
970///
971/// \param FunctionTemplate the function template into which the explicit
972/// template arguments will be substituted.
973///
974/// \param ExplicitTemplateArguments the explicitly-specified template
975/// arguments.
976///
977/// \param NumExplicitTemplateArguments the number of explicitly-specified
978/// template arguments in @p ExplicitTemplateArguments. This value may be zero.
979///
980/// \param Deduced the deduced template arguments, which will be populated
981/// with the converted and checked explicit template arguments.
982///
983/// \param ParamTypes will be populated with the instantiated function
984/// parameters.
985///
986/// \param FunctionType if non-NULL, the result type of the function template
987/// will also be instantiated and the pointed-to value will be updated with
988/// the instantiated function type.
989///
990/// \param Info if substitution fails for any reason, this object will be
991/// populated with more information about the failure.
992///
993/// \returns TDK_Success if substitution was successful, or some failure
994/// condition.
995Sema::TemplateDeductionResult
996Sema::SubstituteExplicitTemplateArguments(
997 FunctionTemplateDecl *FunctionTemplate,
998 const TemplateArgument *ExplicitTemplateArgs,
999 unsigned NumExplicitTemplateArgs,
1000 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1001 llvm::SmallVectorImpl<QualType> &ParamTypes,
1002 QualType *FunctionType,
1003 TemplateDeductionInfo &Info) {
1004 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1005 TemplateParameterList *TemplateParams
1006 = FunctionTemplate->getTemplateParameters();
1007
1008 if (NumExplicitTemplateArgs == 0) {
1009 // No arguments to substitute; just copy over the parameter types and
1010 // fill in the function type.
1011 for (FunctionDecl::param_iterator P = Function->param_begin(),
1012 PEnd = Function->param_end();
1013 P != PEnd;
1014 ++P)
1015 ParamTypes.push_back((*P)->getType());
1016
1017 if (FunctionType)
1018 *FunctionType = Function->getType();
1019 return TDK_Success;
1020 }
1021
1022 // Substitution of the explicit template arguments into a function template
1023 /// is a SFINAE context. Trap any errors that might occur.
1024 SFINAETrap Trap(*this);
1025
1026 // C++ [temp.arg.explicit]p3:
1027 // Template arguments that are present shall be specified in the
1028 // declaration order of their corresponding template-parameters. The
1029 // template argument list shall not specify more template-arguments than
1030 // there are corresponding template-parameters.
1031 TemplateArgumentListBuilder Builder(TemplateParams,
1032 NumExplicitTemplateArgs);
1033
1034 // Enter a new template instantiation context where we check the
1035 // explicitly-specified template arguments against this function template,
1036 // and then substitute them into the function parameter types.
1037 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1038 FunctionTemplate, Deduced.data(), Deduced.size(),
1039 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution);
1040 if (Inst)
1041 return TDK_InstantiationDepth;
1042
1043 if (CheckTemplateArgumentList(FunctionTemplate,
1044 SourceLocation(), SourceLocation(),
1045 ExplicitTemplateArgs,
1046 NumExplicitTemplateArgs,
1047 SourceLocation(),
1048 true,
1049 Builder) || Trap.hasErrorOccurred())
1050 return TDK_InvalidExplicitArguments;
1051
1052 // Form the template argument list from the explicitly-specified
1053 // template arguments.
1054 TemplateArgumentList *ExplicitArgumentList
1055 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1056 Info.reset(ExplicitArgumentList);
1057
1058 // Instantiate the types of each of the function parameters given the
1059 // explicitly-specified template arguments.
1060 for (FunctionDecl::param_iterator P = Function->param_begin(),
1061 PEnd = Function->param_end();
1062 P != PEnd;
1063 ++P) {
1064 QualType ParamType = InstantiateType((*P)->getType(),
1065 *ExplicitArgumentList,
1066 (*P)->getLocation(),
1067 (*P)->getDeclName());
1068 if (ParamType.isNull() || Trap.hasErrorOccurred())
1069 return TDK_SubstitutionFailure;
1070
1071 ParamTypes.push_back(ParamType);
1072 }
1073
1074 // If the caller wants a full function type back, instantiate the return
1075 // type and form that function type.
1076 if (FunctionType) {
1077 // FIXME: exception-specifications?
1078 const FunctionProtoType *Proto
1079 = Function->getType()->getAsFunctionProtoType();
1080 assert(Proto && "Function template does not have a prototype?");
1081
1082 QualType ResultType = InstantiateType(Proto->getResultType(),
1083 *ExplicitArgumentList,
1084 Function->getTypeSpecStartLoc(),
1085 Function->getDeclName());
1086 if (ResultType.isNull() || Trap.hasErrorOccurred())
1087 return TDK_SubstitutionFailure;
1088
1089 *FunctionType = BuildFunctionType(ResultType,
1090 ParamTypes.data(), ParamTypes.size(),
1091 Proto->isVariadic(),
1092 Proto->getTypeQuals(),
1093 Function->getLocation(),
1094 Function->getDeclName());
1095 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1096 return TDK_SubstitutionFailure;
1097 }
1098
1099 // C++ [temp.arg.explicit]p2:
1100 // Trailing template arguments that can be deduced (14.8.2) may be
1101 // omitted from the list of explicit template-arguments. If all of the
1102 // template arguments can be deduced, they may all be omitted; in this
1103 // case, the empty template argument list <> itself may also be omitted.
1104 //
1105 // Take all of the explicitly-specified arguments and put them into the
1106 // set of deduced template arguments.
1107 Deduced.reserve(TemplateParams->size());
1108 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
1109 Deduced.push_back(ExplicitArgumentList->get(I));
1110
1111 return TDK_Success;
1112}
1113
1114/// \brief Finish template argument deduction for a function template,
1115/// checking the deduced template arguments for completeness and forming
1116/// the function template specialization.
1117Sema::TemplateDeductionResult
1118Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
1119 llvm::SmallVectorImpl<TemplateArgument> &Deduced,
1120 FunctionDecl *&Specialization,
1121 TemplateDeductionInfo &Info) {
1122 TemplateParameterList *TemplateParams
1123 = FunctionTemplate->getTemplateParameters();
1124
1125 // C++ [temp.deduct.type]p2:
1126 // [...] or if any template argument remains neither deduced nor
1127 // explicitly specified, template argument deduction fails.
1128 TemplateArgumentListBuilder Builder(TemplateParams, Deduced.size());
1129 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1130 if (Deduced[I].isNull()) {
1131 Info.Param = makeTemplateParameter(
1132 const_cast<Decl *>(TemplateParams->getParam(I)));
1133 return TDK_Incomplete;
1134 }
1135
1136 Builder.Append(Deduced[I]);
1137 }
1138
1139 // Form the template argument list from the deduced template arguments.
1140 TemplateArgumentList *DeducedArgumentList
1141 = new (Context) TemplateArgumentList(Context, Builder, /*TakeArgs=*/true);
1142 Info.reset(DeducedArgumentList);
1143
1144 // Template argument deduction for function templates in a SFINAE context.
1145 // Trap any errors that might occur.
1146 SFINAETrap Trap(*this);
1147
1148 // Enter a new template instantiation context while we instantiate the
1149 // actual function declaration.
1150 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
1151 FunctionTemplate, Deduced.data(), Deduced.size(),
1152 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
1153 if (Inst)
1154 return TDK_InstantiationDepth;
1155
1156 // Substitute the deduced template arguments into the function template
1157 // declaration to produce the function template specialization.
1158 Specialization = cast_or_null<FunctionDecl>(
1159 InstantiateDecl(FunctionTemplate->getTemplatedDecl(),
1160 FunctionTemplate->getDeclContext(),
1161 *DeducedArgumentList));
1162 if (!Specialization)
1163 return TDK_SubstitutionFailure;
1164
1165 // If the template argument list is owned by the function template
1166 // specialization, release it.
1167 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList)
1168 Info.take();
1169
1170 // There may have been an error that did not prevent us from constructing a
1171 // declaration. Mark the declaration invalid and return with a substitution
1172 // failure.
1173 if (Trap.hasErrorOccurred()) {
1174 Specialization->setInvalidDecl(true);
1175 return TDK_SubstitutionFailure;
1176 }
1177
1178 return TDK_Success;
1179}
1180
Douglas Gregore53060f2009-06-25 22:08:12 +00001181/// \brief Perform template argument deduction from a function call
1182/// (C++ [temp.deduct.call]).
1183///
1184/// \param FunctionTemplate the function template for which we are performing
1185/// template argument deduction.
1186///
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001187/// \param HasExplicitTemplateArgs whether any template arguments were
1188/// explicitly specified.
1189///
1190/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1191/// the explicitly-specified template arguments.
1192///
1193/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1194/// the number of explicitly-specified template arguments in
1195/// @p ExplicitTemplateArguments. This value may be zero.
1196///
Douglas Gregore53060f2009-06-25 22:08:12 +00001197/// \param Args the function call arguments
1198///
1199/// \param NumArgs the number of arguments in Args
1200///
1201/// \param Specialization if template argument deduction was successful,
1202/// this will be set to the function template specialization produced by
1203/// template argument deduction.
1204///
1205/// \param Info the argument will be updated to provide additional information
1206/// about template argument deduction.
1207///
1208/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001209Sema::TemplateDeductionResult
1210Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001211 bool HasExplicitTemplateArgs,
1212 const TemplateArgument *ExplicitTemplateArgs,
1213 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001214 Expr **Args, unsigned NumArgs,
1215 FunctionDecl *&Specialization,
1216 TemplateDeductionInfo &Info) {
1217 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001218
Douglas Gregore53060f2009-06-25 22:08:12 +00001219 // C++ [temp.deduct.call]p1:
1220 // Template argument deduction is done by comparing each function template
1221 // parameter type (call it P) with the type of the corresponding argument
1222 // of the call (call it A) as described below.
1223 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001224 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001225 return TDK_TooFewArguments;
1226 else if (NumArgs > Function->getNumParams()) {
1227 const FunctionProtoType *Proto
1228 = Function->getType()->getAsFunctionProtoType();
1229 if (!Proto->isVariadic())
1230 return TDK_TooManyArguments;
1231
1232 CheckArgs = Function->getNumParams();
1233 }
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001234
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001235 // The types of the parameters from which we will perform template argument
1236 // deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001237 TemplateParameterList *TemplateParams
1238 = FunctionTemplate->getTemplateParameters();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001239 llvm::SmallVector<TemplateArgument, 4> Deduced;
1240 llvm::SmallVector<QualType, 4> ParamTypes;
1241 if (NumExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001242 TemplateDeductionResult Result =
1243 SubstituteExplicitTemplateArguments(FunctionTemplate,
1244 ExplicitTemplateArgs,
1245 NumExplicitTemplateArgs,
1246 Deduced,
1247 ParamTypes,
1248 0,
1249 Info);
1250 if (Result)
1251 return Result;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001252 } else {
1253 // Just fill in the parameter types from the function declaration.
1254 for (unsigned I = 0; I != CheckArgs; ++I)
1255 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1256 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00001257
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001258 // Deduce template arguments from the function parameters.
1259 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001260 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001261 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001262 QualType ArgType = Args[I]->getType();
Douglas Gregor500d3312009-06-26 18:27:22 +00001263
Douglas Gregore53060f2009-06-25 22:08:12 +00001264 // C++ [temp.deduct.call]p2:
1265 // If P is not a reference type:
1266 QualType CanonParamType = Context.getCanonicalType(ParamType);
Douglas Gregor500d3312009-06-26 18:27:22 +00001267 bool ParamWasReference = isa<ReferenceType>(CanonParamType);
1268 if (!ParamWasReference) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001269 // - If A is an array type, the pointer type produced by the
1270 // array-to-pointer standard conversion (4.2) is used in place of
1271 // A for type deduction; otherwise,
1272 if (ArgType->isArrayType())
1273 ArgType = Context.getArrayDecayedType(ArgType);
1274 // - If A is a function type, the pointer type produced by the
1275 // function-to-pointer standard conversion (4.3) is used in place
1276 // of A for type deduction; otherwise,
1277 else if (ArgType->isFunctionType())
1278 ArgType = Context.getPointerType(ArgType);
1279 else {
1280 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1281 // type are ignored for type deduction.
1282 QualType CanonArgType = Context.getCanonicalType(ArgType);
1283 if (CanonArgType.getCVRQualifiers())
1284 ArgType = CanonArgType.getUnqualifiedType();
1285 }
1286 }
1287
1288 // C++0x [temp.deduct.call]p3:
1289 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1290 // are ignored for type deduction.
1291 if (CanonParamType.getCVRQualifiers())
1292 ParamType = CanonParamType.getUnqualifiedType();
Ted Kremenek35366a62009-07-17 17:50:17 +00001293 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001294 // [...] If P is a reference type, the type referred to by P is used
1295 // for type deduction.
1296 ParamType = ParamRefType->getPointeeType();
1297
1298 // [...] If P is of the form T&&, where T is a template parameter, and
1299 // the argument is an lvalue, the type A& is used in place of A for
1300 // type deduction.
1301 if (isa<RValueReferenceType>(ParamRefType) &&
1302 ParamRefType->getAsTemplateTypeParmType() &&
1303 Args[I]->isLvalue(Context) == Expr::LV_Valid)
1304 ArgType = Context.getLValueReferenceType(ArgType);
1305 }
1306
1307 // C++0x [temp.deduct.call]p4:
1308 // In general, the deduction process attempts to find template argument
1309 // values that will make the deduced A identical to A (after the type A
1310 // is transformed as described above). [...]
Douglas Gregor508f1c82009-06-26 23:10:12 +00001311 unsigned TDF = 0;
1312
1313 // - If the original P is a reference type, the deduced A (i.e., the
1314 // type referred to by the reference) can be more cv-qualified than
1315 // the transformed A.
1316 if (ParamWasReference)
1317 TDF |= TDF_ParamWithReferenceType;
1318 // - The transformed A can be another pointer or pointer to member
1319 // type that can be converted to the deduced A via a qualification
1320 // conversion (4.4).
1321 if (ArgType->isPointerType() || ArgType->isMemberPointerType())
1322 TDF |= TDF_IgnoreQualifiers;
Douglas Gregor41128772009-06-26 23:27:24 +00001323 // - If P is a class and P has the form simple-template-id, then the
1324 // transformed A can be a derived class of the deduced A. Likewise,
1325 // if P is a pointer to a class of the form simple-template-id, the
1326 // transformed A can be a pointer to a derived class pointed to by
1327 // the deduced A.
1328 if (isSimpleTemplateIdType(ParamType) ||
1329 (isa<PointerType>(ParamType) &&
1330 isSimpleTemplateIdType(
Ted Kremenek35366a62009-07-17 17:50:17 +00001331 ParamType->getAsPointerType()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00001332 TDF |= TDF_DerivedClass;
1333
Douglas Gregore53060f2009-06-25 22:08:12 +00001334 if (TemplateDeductionResult Result
1335 = ::DeduceTemplateArguments(Context, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00001336 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001337 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00001338 return Result;
1339
Douglas Gregor8fdc3c42009-07-07 23:12:18 +00001340 // FIXME: C++0x [temp.deduct.call] paragraphs 6-9 deal with function
Douglas Gregore53060f2009-06-25 22:08:12 +00001341 // pointer parameters.
1342 }
Douglas Gregore53060f2009-06-25 22:08:12 +00001343
Douglas Gregor83314aa2009-07-08 20:55:45 +00001344 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1345 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00001346}
1347
Douglas Gregor83314aa2009-07-08 20:55:45 +00001348/// \brief Deduce template arguments when taking the address of a function
1349/// template (C++ [temp.deduct.funcaddr]).
1350///
1351/// \param FunctionTemplate the function template for which we are performing
1352/// template argument deduction.
1353///
1354/// \param HasExplicitTemplateArgs whether any template arguments were
1355/// explicitly specified.
1356///
1357/// \param ExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1358/// the explicitly-specified template arguments.
1359///
1360/// \param NumExplicitTemplateArguments when @p HasExplicitTemplateArgs is true,
1361/// the number of explicitly-specified template arguments in
1362/// @p ExplicitTemplateArguments. This value may be zero.
1363///
1364/// \param ArgFunctionType the function type that will be used as the
1365/// "argument" type (A) when performing template argument deduction from the
1366/// function template's function type.
1367///
1368/// \param Specialization if template argument deduction was successful,
1369/// this will be set to the function template specialization produced by
1370/// template argument deduction.
1371///
1372/// \param Info the argument will be updated to provide additional information
1373/// about template argument deduction.
1374///
1375/// \returns the result of template argument deduction.
1376Sema::TemplateDeductionResult
1377Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1378 bool HasExplicitTemplateArgs,
1379 const TemplateArgument *ExplicitTemplateArgs,
1380 unsigned NumExplicitTemplateArgs,
1381 QualType ArgFunctionType,
1382 FunctionDecl *&Specialization,
1383 TemplateDeductionInfo &Info) {
1384 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1385 TemplateParameterList *TemplateParams
1386 = FunctionTemplate->getTemplateParameters();
1387 QualType FunctionType = Function->getType();
1388
1389 // Substitute any explicit template arguments.
1390 llvm::SmallVector<TemplateArgument, 4> Deduced;
1391 llvm::SmallVector<QualType, 4> ParamTypes;
1392 if (HasExplicitTemplateArgs) {
1393 if (TemplateDeductionResult Result
1394 = SubstituteExplicitTemplateArguments(FunctionTemplate,
1395 ExplicitTemplateArgs,
1396 NumExplicitTemplateArgs,
1397 Deduced, ParamTypes,
1398 &FunctionType, Info))
1399 return Result;
1400 }
1401
1402 // Template argument deduction for function templates in a SFINAE context.
1403 // Trap any errors that might occur.
1404 SFINAETrap Trap(*this);
1405
1406 // Deduce template arguments from the function type.
1407 Deduced.resize(TemplateParams->size());
1408 if (TemplateDeductionResult Result
1409 = ::DeduceTemplateArguments(Context, TemplateParams,
1410 FunctionType, ArgFunctionType, Info,
1411 Deduced, 0))
1412 return Result;
1413
1414 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1415 Specialization, Info);
1416}
1417
1418
Douglas Gregor031a5882009-06-13 00:26:55 +00001419static void
1420MarkDeducedTemplateParameters(Sema &SemaRef,
1421 const TemplateArgument &TemplateArg,
1422 llvm::SmallVectorImpl<bool> &Deduced);
1423
1424/// \brief Mark the template arguments that are deduced by the given
1425/// expression.
1426static void
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001427MarkDeducedTemplateParameters(const Expr *E,
1428 llvm::SmallVectorImpl<bool> &Deduced) {
1429 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor031a5882009-06-13 00:26:55 +00001430 if (!E)
1431 return;
1432
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001433 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00001434 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
1435 if (!NTTP)
1436 return;
1437
1438 Deduced[NTTP->getIndex()] = true;
1439}
1440
1441/// \brief Mark the template parameters that are deduced by the given
1442/// type.
1443static void
1444MarkDeducedTemplateParameters(Sema &SemaRef, QualType T,
1445 llvm::SmallVectorImpl<bool> &Deduced) {
1446 // Non-dependent types have nothing deducible
1447 if (!T->isDependentType())
1448 return;
1449
1450 T = SemaRef.Context.getCanonicalType(T);
1451 switch (T->getTypeClass()) {
1452 case Type::ExtQual:
1453 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001454 QualType(cast<ExtQualType>(T)->getBaseType(), 0),
Douglas Gregor031a5882009-06-13 00:26:55 +00001455 Deduced);
1456 break;
1457
1458 case Type::Pointer:
1459 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001460 cast<PointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001461 Deduced);
1462 break;
1463
1464 case Type::BlockPointer:
1465 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001466 cast<BlockPointerType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001467 Deduced);
1468 break;
1469
1470 case Type::LValueReference:
1471 case Type::RValueReference:
1472 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001473 cast<ReferenceType>(T)->getPointeeType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001474 Deduced);
1475 break;
1476
1477 case Type::MemberPointer: {
1478 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
1479 MarkDeducedTemplateParameters(SemaRef, MemPtr->getPointeeType(), Deduced);
1480 MarkDeducedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
1481 Deduced);
1482 break;
1483 }
1484
1485 case Type::DependentSizedArray:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001486 MarkDeducedTemplateParameters(cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001487 Deduced);
1488 // Fall through to check the element type
1489
1490 case Type::ConstantArray:
1491 case Type::IncompleteArray:
1492 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001493 cast<ArrayType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001494 Deduced);
1495 break;
1496
1497 case Type::Vector:
1498 case Type::ExtVector:
1499 MarkDeducedTemplateParameters(SemaRef,
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001500 cast<VectorType>(T)->getElementType(),
Douglas Gregor031a5882009-06-13 00:26:55 +00001501 Deduced);
1502 break;
1503
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001504 case Type::DependentSizedExtVector: {
1505 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001506 = cast<DependentSizedExtVectorType>(T);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001507 MarkDeducedTemplateParameters(SemaRef, VecType->getElementType(), Deduced);
1508 MarkDeducedTemplateParameters(VecType->getSizeExpr(), Deduced);
1509 break;
1510 }
1511
Douglas Gregor031a5882009-06-13 00:26:55 +00001512 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001513 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001514 MarkDeducedTemplateParameters(SemaRef, Proto->getResultType(), Deduced);
1515 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
1516 MarkDeducedTemplateParameters(SemaRef, Proto->getArgType(I), Deduced);
1517 break;
1518 }
1519
1520 case Type::TemplateTypeParm:
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001521 Deduced[cast<TemplateTypeParmType>(T)->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00001522 break;
1523
1524 case Type::TemplateSpecialization: {
1525 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00001526 = cast<TemplateSpecializationType>(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00001527 if (TemplateDecl *Template = Spec->getTemplateName().getAsTemplateDecl())
1528 if (TemplateTemplateParmDecl *TTP
1529 = dyn_cast<TemplateTemplateParmDecl>(Template))
1530 Deduced[TTP->getIndex()] = true;
1531
1532 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
1533 MarkDeducedTemplateParameters(SemaRef, Spec->getArg(I), Deduced);
1534
1535 break;
1536 }
1537
1538 // None of these types have any deducible parts.
1539 case Type::Builtin:
1540 case Type::FixedWidthInt:
1541 case Type::Complex:
1542 case Type::VariableArray:
1543 case Type::FunctionNoProto:
1544 case Type::Record:
1545 case Type::Enum:
1546 case Type::Typename:
1547 case Type::ObjCInterface:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001548 case Type::ObjCObjectPointer:
Douglas Gregor031a5882009-06-13 00:26:55 +00001549#define TYPE(Class, Base)
1550#define ABSTRACT_TYPE(Class, Base)
1551#define DEPENDENT_TYPE(Class, Base)
1552#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1553#include "clang/AST/TypeNodes.def"
1554 break;
1555 }
1556}
1557
1558/// \brief Mark the template parameters that are deduced by this
1559/// template argument.
1560static void
1561MarkDeducedTemplateParameters(Sema &SemaRef,
1562 const TemplateArgument &TemplateArg,
1563 llvm::SmallVectorImpl<bool> &Deduced) {
1564 switch (TemplateArg.getKind()) {
1565 case TemplateArgument::Null:
1566 case TemplateArgument::Integral:
1567 break;
1568
1569 case TemplateArgument::Type:
1570 MarkDeducedTemplateParameters(SemaRef, TemplateArg.getAsType(), Deduced);
1571 break;
1572
1573 case TemplateArgument::Declaration:
1574 if (TemplateTemplateParmDecl *TTP
1575 = dyn_cast<TemplateTemplateParmDecl>(TemplateArg.getAsDecl()))
1576 Deduced[TTP->getIndex()] = true;
1577 break;
1578
1579 case TemplateArgument::Expression:
1580 MarkDeducedTemplateParameters(TemplateArg.getAsExpr(), Deduced);
1581 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001582 case TemplateArgument::Pack:
1583 assert(0 && "FIXME: Implement!");
1584 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00001585 }
1586}
1587
1588/// \brief Mark the template parameters can be deduced by the given
1589/// template argument list.
1590///
1591/// \param TemplateArgs the template argument list from which template
1592/// parameters will be deduced.
1593///
1594/// \param Deduced a bit vector whose elements will be set to \c true
1595/// to indicate when the corresponding template parameter will be
1596/// deduced.
1597void
1598Sema::MarkDeducedTemplateParameters(const TemplateArgumentList &TemplateArgs,
1599 llvm::SmallVectorImpl<bool> &Deduced) {
1600 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1601 ::MarkDeducedTemplateParameters(*this, TemplateArgs[I], Deduced);
1602}