blob: 221b122b741c9c97243aceae3ecfdb19faf5be87 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000023#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000024
25namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000026 using namespace sema;
27
Douglas Gregor508f1c82009-06-26 23:10:12 +000028 /// \brief Various flags that control template argument deduction.
29 ///
30 /// These flags can be bitwise-OR'd together.
31 enum TemplateDeductionFlags {
32 /// \brief No template argument deduction flags, which indicates the
33 /// strictest results for template argument deduction (as used for, e.g.,
34 /// matching class template partial specializations).
35 TDF_None = 0,
36 /// \brief Within template argument deduction from a function call, we are
37 /// matching with a parameter type for which the original parameter was
38 /// a reference.
39 TDF_ParamWithReferenceType = 0x1,
40 /// \brief Within template argument deduction from a function call, we
41 /// are matching in a case where we ignore cv-qualifiers.
42 TDF_IgnoreQualifiers = 0x02,
43 /// \brief Within template argument deduction from a function call,
44 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000045 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000046 TDF_DerivedClass = 0x04,
47 /// \brief Allow non-dependent types to differ, e.g., when performing
48 /// template argument deduction from a function call where conversions
49 /// may apply.
50 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000051 };
52}
53
Douglas Gregor0b9247f2009-06-04 00:03:07 +000054using namespace clang;
55
Douglas Gregor9d0e4412010-03-26 05:50:28 +000056/// \brief Compare two APSInts, extending and switching the sign as
57/// necessary to compare their values regardless of underlying type.
58static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
59 if (Y.getBitWidth() > X.getBitWidth())
60 X.extend(Y.getBitWidth());
61 else if (Y.getBitWidth() < X.getBitWidth())
62 Y.extend(X.getBitWidth());
63
64 // If there is a signedness mismatch, correct it.
65 if (X.isSigned() != Y.isSigned()) {
66 // If the signed value is negative, then the values cannot be the same.
67 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
68 return false;
69
70 Y.setIsSigned(true);
71 X.setIsSigned(true);
72 }
73
74 return X == Y;
75}
76
Douglas Gregorf67875d2009-06-12 18:26:56 +000077static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000078DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000079 TemplateParameterList *TemplateParams,
80 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000081 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000082 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +000083 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000084
Douglas Gregor199d9912009-06-05 00:53:49 +000085/// \brief If the given expression is of a form that permits the deduction
86/// of a non-type template parameter, return the declaration of that
87/// non-type template parameter.
88static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
89 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
90 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +000091
Douglas Gregor199d9912009-06-05 00:53:49 +000092 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
93 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000094
Douglas Gregor199d9912009-06-05 00:53:49 +000095 return 0;
96}
97
Mike Stump1eb44332009-09-09 15:08:12 +000098/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +000099/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000100static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000101DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000102 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000103 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000104 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000105 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000106 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000107 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000108 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Douglas Gregor199d9912009-06-05 00:53:49 +0000110 if (Deduced[NTTP->getIndex()].isNull()) {
Douglas Gregor02024a92010-03-28 02:42:43 +0000111 Deduced[NTTP->getIndex()] = DeducedTemplateArgument(Value, ValueType,
112 DeducedFromArrayBound);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000113 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000114 }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000116 if (Deduced[NTTP->getIndex()].getKind() != TemplateArgument::Integral) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000117 Info.Param = NTTP;
118 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000119 Info.SecondArg = TemplateArgument(Value, ValueType);
120 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000121 }
122
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000123 // Extent the smaller of the two values.
124 llvm::APSInt PrevValue = *Deduced[NTTP->getIndex()].getAsIntegral();
125 if (!hasSameExtendedValue(PrevValue, Value)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000126 Info.Param = NTTP;
127 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000128 Info.SecondArg = TemplateArgument(Value, ValueType);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000129 return Sema::TDK_Inconsistent;
130 }
131
Douglas Gregor02024a92010-03-28 02:42:43 +0000132 if (!DeducedFromArrayBound)
133 Deduced[NTTP->getIndex()].setDeducedFromArrayBound(false);
134
Douglas Gregorf67875d2009-06-12 18:26:56 +0000135 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000136}
137
Mike Stump1eb44332009-09-09 15:08:12 +0000138/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000139/// from the given type- or value-dependent expression.
140///
141/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000142static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000143DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000144 NonTypeTemplateParmDecl *NTTP,
145 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000146 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000147 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000148 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000149 "Cannot deduce non-type template argument with depth > 0");
150 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
151 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor199d9912009-06-05 00:53:49 +0000153 if (Deduced[NTTP->getIndex()].isNull()) {
John McCall3fa5cae2010-10-26 07:05:15 +0000154 Deduced[NTTP->getIndex()] = TemplateArgument(Value);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000155 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Douglas Gregor199d9912009-06-05 00:53:49 +0000158 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
Mike Stump1eb44332009-09-09 15:08:12 +0000159 // Okay, we deduced a constant in one case and a dependent expression
160 // in another case. FIXME: Later, we will check that instantiating the
Douglas Gregor199d9912009-06-05 00:53:49 +0000161 // dependent expression gives us the constant value.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000162 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000163 }
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000165 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
166 // Compare the expressions for equality
167 llvm::FoldingSetNodeID ID1, ID2;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000168 Deduced[NTTP->getIndex()].getAsExpr()->Profile(ID1, S.Context, true);
169 Value->Profile(ID2, S.Context, true);
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000170 if (ID1 == ID2)
171 return Sema::TDK_Success;
172
173 // FIXME: Fill in argument mismatch information
174 return Sema::TDK_NonDeducedMismatch;
175 }
176
Douglas Gregorf67875d2009-06-12 18:26:56 +0000177 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000178}
179
Douglas Gregor15755cb2009-11-13 23:45:44 +0000180/// \brief Deduce the value of the given non-type template parameter
181/// from the given declaration.
182///
183/// \returns true if deduction succeeded, false otherwise.
184static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000185DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000186 NonTypeTemplateParmDecl *NTTP,
187 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000188 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000189 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000190 assert(NTTP->getDepth() == 0 &&
191 "Cannot deduce non-type template argument with depth > 0");
192
193 if (Deduced[NTTP->getIndex()].isNull()) {
194 Deduced[NTTP->getIndex()] = TemplateArgument(D->getCanonicalDecl());
195 return Sema::TDK_Success;
196 }
197
198 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
199 // Okay, we deduced a declaration in one case and a dependent expression
200 // in another case.
201 return Sema::TDK_Success;
202 }
203
204 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Declaration) {
205 // Compare the declarations for equality
206 if (Deduced[NTTP->getIndex()].getAsDecl()->getCanonicalDecl() ==
207 D->getCanonicalDecl())
208 return Sema::TDK_Success;
209
210 // FIXME: Fill in argument mismatch information
211 return Sema::TDK_NonDeducedMismatch;
212 }
213
214 return Sema::TDK_Success;
215}
216
Douglas Gregorf67875d2009-06-12 18:26:56 +0000217static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000218DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000219 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000220 TemplateName Param,
221 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000222 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000223 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000224 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000225 if (!ParamDecl) {
226 // The parameter type is dependent and is not a template template parameter,
227 // so there is nothing that we can deduce.
228 return Sema::TDK_Success;
229 }
230
231 if (TemplateTemplateParmDecl *TempParam
232 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
233 // Bind the template template parameter to the given template name.
234 TemplateArgument &ExistingArg = Deduced[TempParam->getIndex()];
235 if (ExistingArg.isNull()) {
236 // This is the first deduction for this template template parameter.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000237 ExistingArg = TemplateArgument(S.Context.getCanonicalTemplateName(Arg));
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000238 return Sema::TDK_Success;
239 }
240
241 // Verify that the previous binding matches this deduction.
242 assert(ExistingArg.getKind() == TemplateArgument::Template);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000243 if (S.Context.hasSameTemplateName(ExistingArg.getAsTemplate(), Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000244 return Sema::TDK_Success;
245
246 // Inconsistent deduction.
247 Info.Param = TempParam;
248 Info.FirstArg = ExistingArg;
249 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000250 return Sema::TDK_Inconsistent;
251 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000252
253 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000254 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000255 return Sema::TDK_Success;
256
257 // Mismatch of non-dependent template parameter to argument.
258 Info.FirstArg = TemplateArgument(Param);
259 Info.SecondArg = TemplateArgument(Arg);
260 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000261}
262
Mike Stump1eb44332009-09-09 15:08:12 +0000263/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000264/// type (which is a template-id) with the template argument type.
265///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000266/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000267///
268/// \param TemplateParams the template parameters that we are deducing
269///
270/// \param Param the parameter type
271///
272/// \param Arg the argument type
273///
274/// \param Info information about the template argument deduction itself
275///
276/// \param Deduced the deduced template arguments
277///
278/// \returns the result of template argument deduction so far. Note that a
279/// "success" result means that template argument deduction has not yet failed,
280/// but it may still fail, later, for other reasons.
281static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000282DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000283 TemplateParameterList *TemplateParams,
284 const TemplateSpecializationType *Param,
285 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000286 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000287 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000288 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000290 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000291 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000292 = dyn_cast<TemplateSpecializationType>(Arg)) {
293 // Perform template argument deduction for the template name.
294 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000295 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000296 Param->getTemplateName(),
297 SpecArg->getTemplateName(),
298 Info, Deduced))
299 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000302 // Perform template argument deduction on each template
303 // argument.
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000304 unsigned NumArgs = std::min(SpecArg->getNumArgs(), Param->getNumArgs());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000305 for (unsigned I = 0; I != NumArgs; ++I)
306 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000307 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000308 Param->getArg(I),
309 SpecArg->getArg(I),
310 Info, Deduced))
311 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000313 return Sema::TDK_Success;
314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000316 // If the argument type is a class template specialization, we
317 // perform template argument deduction using its template
318 // arguments.
319 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
320 if (!RecordArg)
321 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
323 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000324 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
325 if (!SpecArg)
326 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000328 // Perform template argument deduction for the template name.
329 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000330 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000331 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000332 Param->getTemplateName(),
333 TemplateName(SpecArg->getSpecializedTemplate()),
334 Info, Deduced))
335 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000337 unsigned NumArgs = Param->getNumArgs();
338 const TemplateArgumentList &ArgArgs = SpecArg->getTemplateArgs();
339 if (NumArgs != ArgArgs.size())
340 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000342 for (unsigned I = 0; I != NumArgs; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +0000343 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000344 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000345 Param->getArg(I),
346 ArgArgs.get(I),
347 Info, Deduced))
348 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000350 return Sema::TDK_Success;
351}
352
John McCallcd05e812010-08-28 22:14:41 +0000353/// \brief Determines whether the given type is an opaque type that
354/// might be more qualified when instantiated.
355static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
356 switch (T->getTypeClass()) {
357 case Type::TypeOfExpr:
358 case Type::TypeOf:
359 case Type::DependentName:
360 case Type::Decltype:
361 case Type::UnresolvedUsing:
362 return true;
363
364 case Type::ConstantArray:
365 case Type::IncompleteArray:
366 case Type::VariableArray:
367 case Type::DependentSizedArray:
368 return IsPossiblyOpaquelyQualifiedType(
369 cast<ArrayType>(T)->getElementType());
370
371 default:
372 return false;
373 }
374}
375
Douglas Gregor500d3312009-06-26 18:27:22 +0000376/// \brief Deduce the template arguments by comparing the parameter type and
377/// the argument type (C++ [temp.deduct.type]).
378///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000379/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000380///
381/// \param TemplateParams the template parameters that we are deducing
382///
383/// \param ParamIn the parameter type
384///
385/// \param ArgIn the argument type
386///
387/// \param Info information about the template argument deduction itself
388///
389/// \param Deduced the deduced template arguments
390///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000391/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000392/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000393///
394/// \returns the result of template argument deduction so far. Note that a
395/// "success" result means that template argument deduction has not yet failed,
396/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000397static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000398DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000399 TemplateParameterList *TemplateParams,
400 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000401 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000402 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000403 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000404 // We only want to look at the canonical types, since typedefs and
405 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000406 QualType Param = S.Context.getCanonicalType(ParamIn);
407 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000408
Douglas Gregor500d3312009-06-26 18:27:22 +0000409 // C++0x [temp.deduct.call]p4 bullet 1:
410 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000411 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000412 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000413 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000414 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000415 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000416 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
417 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000418 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000421 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000422 if (!Param->isDependentType()) {
423 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
424
425 return Sema::TDK_NonDeducedMismatch;
426 }
427
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000428 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000429 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000430
Douglas Gregor199d9912009-06-05 00:53:49 +0000431 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000432 // A template type argument T, a template template argument TT or a
433 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000434 // the following forms:
435 //
436 // T
437 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000438 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000439 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000440 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000441 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000443 // If the argument type is an array type, move the qualifiers up to the
444 // top level, so they can be matched with the qualifiers on the parameter.
445 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000446 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000447 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000448 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000449 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000450 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000451 RecanonicalizeArg = true;
452 }
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000455 // The argument type can not be less qualified than the parameter
456 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000457 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000458 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000459 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000460 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000461 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000462 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000463
464 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000465 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000466 QualType DeducedType = Arg;
467 DeducedType.removeCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000468 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000469 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000471 if (Deduced[Index].isNull())
John McCall833ca992009-10-29 08:12:44 +0000472 Deduced[Index] = TemplateArgument(DeducedType);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000473 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000474 // C++ [temp.deduct.type]p2:
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000475 // [...] If type deduction cannot be done for any P/A pair, or if for
Mike Stump1eb44332009-09-09 15:08:12 +0000476 // any pair the deduction leads to more than one possible set of
477 // deduced values, or if different pairs yield different deduced
478 // values, or if any template argument remains neither deduced nor
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000479 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000480 if (Deduced[Index].getAsType() != DeducedType) {
Mike Stump1eb44332009-09-09 15:08:12 +0000481 Info.Param
Douglas Gregorf67875d2009-06-12 18:26:56 +0000482 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
483 Info.FirstArg = Deduced[Index];
John McCall833ca992009-10-29 08:12:44 +0000484 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000485 return Sema::TDK_Inconsistent;
486 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000487 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000488 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000489 }
490
Douglas Gregorf67875d2009-06-12 18:26:56 +0000491 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000492 Info.FirstArg = TemplateArgument(ParamIn);
493 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000494
Douglas Gregor508f1c82009-06-26 23:10:12 +0000495 // Check the cv-qualifiers on the parameter and argument types.
496 if (!(TDF & TDF_IgnoreQualifiers)) {
497 if (TDF & TDF_ParamWithReferenceType) {
498 if (Param.isMoreQualifiedThan(Arg))
499 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000500 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000501 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000502 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000503 }
504 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000505
Douglas Gregord560d502009-06-04 00:21:18 +0000506 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000507 // No deduction possible for these types
508 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000509 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregor199d9912009-06-05 00:53:49 +0000511 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000512 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000513 QualType PointeeType;
514 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
515 PointeeType = PointerArg->getPointeeType();
516 } else if (const ObjCObjectPointerType *PointerArg
517 = Arg->getAs<ObjCObjectPointerType>()) {
518 PointeeType = PointerArg->getPointeeType();
519 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000520 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor41128772009-06-26 23:27:24 +0000523 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000524 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000525 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000526 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000527 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor199d9912009-06-05 00:53:49 +0000530 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000531 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000532 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000533 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000534 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000536 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000537 cast<LValueReferenceType>(Param)->getPointeeType(),
538 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000539 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000540 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000541
Douglas Gregor199d9912009-06-05 00:53:49 +0000542 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000543 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000544 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000545 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000546 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000548 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000549 cast<RValueReferenceType>(Param)->getPointeeType(),
550 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000551 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Douglas Gregor199d9912009-06-05 00:53:49 +0000554 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000555 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000556 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000557 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000558 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000559 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000560
John McCalle4f26e52010-08-19 00:20:19 +0000561 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000562 return DeduceTemplateArguments(S, TemplateParams,
563 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000564 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000565 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000566 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000567
568 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000569 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000570 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000571 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000572 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000573 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
575 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000576 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000577 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000578 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
John McCalle4f26e52010-08-19 00:20:19 +0000580 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000581 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000582 ConstantArrayParm->getElementType(),
583 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000584 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000585 }
586
Douglas Gregor199d9912009-06-05 00:53:49 +0000587 // type [i]
588 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000589 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000590 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000591 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
John McCalle4f26e52010-08-19 00:20:19 +0000593 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
594
Douglas Gregor199d9912009-06-05 00:53:49 +0000595 // Check the element type of the arrays
596 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000597 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000598 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000599 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000600 DependentArrayParm->getElementType(),
601 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000602 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000603 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Douglas Gregor199d9912009-06-05 00:53:49 +0000605 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000606 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000607 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
608 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000609 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
611 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000612 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000613 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000614 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000615 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000616 = dyn_cast<ConstantArrayType>(ArrayArg)) {
617 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000618 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
619 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000620 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000621 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000622 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000623 if (const DependentSizedArrayType *DependentArrayArg
624 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000625 return DeduceNonTypeTemplateArgument(S, NTTP,
Douglas Gregor199d9912009-06-05 00:53:49 +0000626 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000627 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Douglas Gregor199d9912009-06-05 00:53:49 +0000629 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000630 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
633 // type(*)(T)
634 // T(*)()
635 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000636 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000637 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000638 dyn_cast<FunctionProtoType>(Arg);
639 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000640 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000641
642 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000643 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000644
Mike Stump1eb44332009-09-09 15:08:12 +0000645 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000646 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000647 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000649 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000650 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000652 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000653 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000654
Anders Carlssona27fad52009-06-08 15:19:08 +0000655 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000656 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000657 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000658 FunctionProtoParam->getResultType(),
659 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000660 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000661 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Anders Carlssona27fad52009-06-08 15:19:08 +0000663 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
664 // Check argument types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000665 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000666 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000667 FunctionProtoParam->getArgType(I),
668 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000669 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000670 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Douglas Gregorf67875d2009-06-12 18:26:56 +0000673 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
John McCall3cb0ebd2010-03-10 03:28:59 +0000676 case Type::InjectedClassName: {
677 // Treat a template's injected-class-name as if the template
678 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000679 Param = cast<InjectedClassNameType>(Param)
680 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000681 assert(isa<TemplateSpecializationType>(Param) &&
682 "injected class name is not a template specialization type");
683 // fall through
684 }
685
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000686 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000687 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000688 // TT<T>
689 // TT<i>
690 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000691 case Type::TemplateSpecialization: {
692 const TemplateSpecializationType *SpecParam
693 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000695 // Try to deduce template arguments from the template-id.
696 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000697 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000698 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000700 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000701 // C++ [temp.deduct.call]p3b3:
702 // If P is a class, and P has the form template-id, then A can be a
703 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000704 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000705 // class pointed to by the deduced A.
706 //
707 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000708 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000709 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000710 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
711 // We cannot inspect base classes as part of deduction when the type
712 // is incomplete, so either instantiate any templates necessary to
713 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000714 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000715 return Result;
716
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000717 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000718 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000719 // ToVisit is our stack of records that we still need to visit.
720 llvm::SmallPtrSet<const RecordType *, 8> Visited;
721 llvm::SmallVector<const RecordType *, 8> ToVisit;
722 ToVisit.push_back(RecordT);
723 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000724 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
725 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000726 while (!ToVisit.empty()) {
727 // Retrieve the next class in the inheritance hierarchy.
728 const RecordType *NextT = ToVisit.back();
729 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000731 // If we have already seen this type, skip it.
732 if (!Visited.insert(NextT))
733 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000735 // If this is a base class, try to perform template argument
736 // deduction from it.
737 if (NextT != RecordT) {
738 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000739 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000740 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000742 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000743 // note that we had some success. Otherwise, ignore any deductions
744 // from this base class.
745 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000746 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000747 DeducedOrig = Deduced;
748 }
749 else
750 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000753 // Visit base classes
754 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
755 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
756 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000757 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000758 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000759 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000760 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000761 }
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000764 if (Successful)
765 return Sema::TDK_Success;
766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000770 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000771 }
772
Douglas Gregor637a4092009-06-10 23:47:09 +0000773 // T type::*
774 // T T::*
775 // T (type::*)()
776 // type (T::*)()
777 // type (type::*)(T)
778 // type (T::*)(T)
779 // T (type::*)(T)
780 // T (T::*)()
781 // T (T::*)(T)
782 case Type::MemberPointer: {
783 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
784 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
785 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000786 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000787
Douglas Gregorf67875d2009-06-12 18:26:56 +0000788 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000789 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000790 MemPtrParam->getPointeeType(),
791 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000792 Info, Deduced,
793 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000794 return Result;
795
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000796 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000797 QualType(MemPtrParam->getClass(), 0),
798 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000799 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000800 }
801
Anders Carlsson9a917e42009-06-12 22:56:54 +0000802 // (clang extension)
803 //
Mike Stump1eb44332009-09-09 15:08:12 +0000804 // type(^)(T)
805 // T(^)()
806 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000807 case Type::BlockPointer: {
808 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
809 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Anders Carlsson859ba502009-06-12 16:23:10 +0000811 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000812 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000814 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000815 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000816 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000817 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000818 }
819
Douglas Gregor637a4092009-06-10 23:47:09 +0000820 case Type::TypeOfExpr:
821 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000822 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000823 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000824 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000825
Douglas Gregord560d502009-06-04 00:21:18 +0000826 default:
827 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000828 }
829
830 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000831 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000832}
833
Douglas Gregorf67875d2009-06-12 18:26:56 +0000834static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000835DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000836 TemplateParameterList *TemplateParams,
837 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000838 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000839 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000840 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000841 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000842 case TemplateArgument::Null:
843 assert(false && "Null template argument in parameter list");
844 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
846 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000847 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000848 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000849 Arg.getAsType(), Info, Deduced, 0);
850 Info.FirstArg = Param;
851 Info.SecondArg = Arg;
852 return Sema::TDK_NonDeducedMismatch;
853
854 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000855 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000856 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000857 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000858 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000859 Info.FirstArg = Param;
860 Info.SecondArg = Arg;
861 return Sema::TDK_NonDeducedMismatch;
862
Douglas Gregor199d9912009-06-05 00:53:49 +0000863 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000864 if (Arg.getKind() == TemplateArgument::Declaration &&
865 Param.getAsDecl()->getCanonicalDecl() ==
866 Arg.getAsDecl()->getCanonicalDecl())
867 return Sema::TDK_Success;
868
Douglas Gregorf67875d2009-06-12 18:26:56 +0000869 Info.FirstArg = Param;
870 Info.SecondArg = Arg;
871 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Douglas Gregor199d9912009-06-05 00:53:49 +0000873 case TemplateArgument::Integral:
874 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000875 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000876 return Sema::TDK_Success;
877
878 Info.FirstArg = Param;
879 Info.SecondArg = Arg;
880 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000881 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000882
883 if (Arg.getKind() == TemplateArgument::Expression) {
884 Info.FirstArg = Param;
885 Info.SecondArg = Arg;
886 return Sema::TDK_NonDeducedMismatch;
887 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000888
Douglas Gregorf67875d2009-06-12 18:26:56 +0000889 Info.FirstArg = Param;
890 Info.SecondArg = Arg;
891 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregor199d9912009-06-05 00:53:49 +0000893 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 = getDeducedParameterFromExpr(Param.getAsExpr())) {
896 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000897 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000898 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000899 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000900 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000901 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000902 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000903 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000904 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +0000905 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000906 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +0000907 Info, Deduced);
908
Douglas Gregorf67875d2009-06-12 18:26:56 +0000909 Info.FirstArg = Param;
910 Info.SecondArg = Arg;
911 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000915 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000916 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000917 case TemplateArgument::Pack:
918 assert(0 && "FIXME: Implement!");
919 break;
Douglas Gregor199d9912009-06-05 00:53:49 +0000920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Douglas Gregorf67875d2009-06-12 18:26:56 +0000922 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000923}
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000926DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000927 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000928 const TemplateArgumentList &ParamList,
929 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +0000930 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000931 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000932 assert(ParamList.size() == ArgList.size());
933 for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000934 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000935 = DeduceTemplateArguments(S, TemplateParams,
Mike Stump1eb44332009-09-09 15:08:12 +0000936 ParamList[I], ArgList[I],
Douglas Gregorf67875d2009-06-12 18:26:56 +0000937 Info, Deduced))
938 return Result;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000939 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000940 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000941}
942
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000943/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +0000944static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000945 const TemplateArgument &X,
946 const TemplateArgument &Y) {
947 if (X.getKind() != Y.getKind())
948 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000950 switch (X.getKind()) {
951 case TemplateArgument::Null:
952 assert(false && "Comparing NULL template argument");
953 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000955 case TemplateArgument::Type:
956 return Context.getCanonicalType(X.getAsType()) ==
957 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000959 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000960 return X.getAsDecl()->getCanonicalDecl() ==
961 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Douglas Gregor788cd062009-11-11 01:00:40 +0000963 case TemplateArgument::Template:
964 return Context.getCanonicalTemplateName(X.getAsTemplate())
965 .getAsVoidPointer() ==
966 Context.getCanonicalTemplateName(Y.getAsTemplate())
967 .getAsVoidPointer();
968
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000969 case TemplateArgument::Integral:
970 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Douglas Gregor788cd062009-11-11 01:00:40 +0000972 case TemplateArgument::Expression: {
973 llvm::FoldingSetNodeID XID, YID;
974 X.getAsExpr()->Profile(XID, Context, true);
975 Y.getAsExpr()->Profile(YID, Context, true);
976 return XID == YID;
977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000979 case TemplateArgument::Pack:
980 if (X.pack_size() != Y.pack_size())
981 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000982
983 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
984 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000985 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +0000986 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000987 if (!isSameTemplateArg(Context, *XP, *YP))
988 return false;
989
990 return true;
991 }
992
993 return false;
994}
995
996/// \brief Helper function to build a TemplateParameter when we don't
997/// know its type statically.
998static TemplateParameter makeTemplateParameter(Decl *D) {
999 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1000 return TemplateParameter(TTP);
1001 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1002 return TemplateParameter(NTTP);
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001004 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1005}
1006
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001007/// Complete template argument deduction for a class template partial
1008/// specialization.
1009static Sema::TemplateDeductionResult
1010FinishTemplateArgumentDeduction(Sema &S,
1011 ClassTemplatePartialSpecializationDecl *Partial,
1012 const TemplateArgumentList &TemplateArgs,
1013 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001014 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001015 // Trap errors.
1016 Sema::SFINAETrap Trap(S);
1017
1018 Sema::ContextRAII SavedContext(S, Partial);
1019
1020 // C++ [temp.deduct.type]p2:
1021 // [...] or if any template argument remains neither deduced nor
1022 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001023 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001024 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1025 if (Deduced[I].isNull()) {
1026 Decl *Param
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001027 = const_cast<NamedDecl *>(
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001028 Partial->getTemplateParameters()->getParam(I));
1029 Info.Param = makeTemplateParameter(Param);
1030 return Sema::TDK_Incomplete;
1031 }
1032
Douglas Gregor910f8002010-11-07 23:05:16 +00001033 Builder.push_back(Deduced[I]);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001034 }
1035
1036 // Form the template argument list from the deduced template arguments.
1037 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001038 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1039 Builder.size());
1040
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001041 Info.reset(DeducedArgumentList);
1042
1043 // Substitute the deduced template arguments into the template
1044 // arguments of the class template partial specialization, and
1045 // verify that the instantiated template arguments are both valid
1046 // and are equivalent to the template arguments originally provided
1047 // to the class template.
1048 // FIXME: Do we have to correct the types of deduced non-type template
1049 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001050 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001051 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1052 const TemplateArgumentLoc *PartialTemplateArgs
1053 = Partial->getTemplateArgsAsWritten();
1054 unsigned N = Partial->getNumTemplateArgsAsWritten();
1055
1056 // Note that we don't provide the langle and rangle locations.
1057 TemplateArgumentListInfo InstArgs;
1058
1059 for (unsigned I = 0; I != N; ++I) {
1060 Decl *Param = const_cast<NamedDecl *>(
1061 ClassTemplate->getTemplateParameters()->getParam(I));
1062 TemplateArgumentLoc InstArg;
1063 if (S.Subst(PartialTemplateArgs[I], InstArg,
1064 MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1065 Info.Param = makeTemplateParameter(Param);
1066 Info.FirstArg = PartialTemplateArgs[I].getArgument();
1067 return Sema::TDK_SubstitutionFailure;
1068 }
1069 InstArgs.addArgument(InstArg);
1070 }
1071
Douglas Gregor910f8002010-11-07 23:05:16 +00001072 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001073 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorec20f462010-05-08 20:07:26 +00001074 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001075 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001076
Douglas Gregor910f8002010-11-07 23:05:16 +00001077 for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1078 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001079
1080 Decl *Param = const_cast<NamedDecl *>(
1081 ClassTemplate->getTemplateParameters()->getParam(I));
1082
1083 if (InstArg.getKind() == TemplateArgument::Expression) {
1084 // When the argument is an expression, check the expression result
1085 // against the actual template parameter to get down to the canonical
1086 // template argument.
1087 Expr *InstExpr = InstArg.getAsExpr();
1088 if (NonTypeTemplateParmDecl *NTTP
1089 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1090 if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1091 Info.Param = makeTemplateParameter(Param);
1092 Info.FirstArg = Partial->getTemplateArgs()[I];
1093 return Sema::TDK_SubstitutionFailure;
1094 }
1095 }
1096 }
1097
1098 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1099 Info.Param = makeTemplateParameter(Param);
1100 Info.FirstArg = TemplateArgs[I];
1101 Info.SecondArg = InstArg;
1102 return Sema::TDK_NonDeducedMismatch;
1103 }
1104 }
1105
1106 if (Trap.hasErrorOccurred())
1107 return Sema::TDK_SubstitutionFailure;
1108
1109 return Sema::TDK_Success;
1110}
1111
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001112/// \brief Perform template argument deduction to determine whether
1113/// the given template arguments match the given class template
1114/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001115Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001116Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001117 const TemplateArgumentList &TemplateArgs,
1118 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001119 // C++ [temp.class.spec.match]p2:
1120 // A partial specialization matches a given actual template
1121 // argument list if the template arguments of the partial
1122 // specialization can be deduced from the actual template argument
1123 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001124 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001125 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001126 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001127 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001128 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001129 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001130 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001131 TemplateArgs, Info, Deduced))
1132 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001133
Douglas Gregor637a4092009-06-10 23:47:09 +00001134 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001135 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001136 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001137 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001138
Douglas Gregorbb260412009-06-14 08:02:22 +00001139 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001140 return Sema::TDK_SubstitutionFailure;
1141
1142 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1143 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001144}
Douglas Gregor031a5882009-06-13 00:26:55 +00001145
Douglas Gregor41128772009-06-26 23:27:24 +00001146/// \brief Determine whether the given type T is a simple-template-id type.
1147static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001148 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001149 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001150 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Douglas Gregor41128772009-06-26 23:27:24 +00001152 return false;
1153}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001154
1155/// \brief Substitute the explicitly-provided template arguments into the
1156/// given function template according to C++ [temp.arg.explicit].
1157///
1158/// \param FunctionTemplate the function template into which the explicit
1159/// template arguments will be substituted.
1160///
Mike Stump1eb44332009-09-09 15:08:12 +00001161/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001162/// arguments.
1163///
Mike Stump1eb44332009-09-09 15:08:12 +00001164/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001165/// with the converted and checked explicit template arguments.
1166///
Mike Stump1eb44332009-09-09 15:08:12 +00001167/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001168/// parameters.
1169///
1170/// \param FunctionType if non-NULL, the result type of the function template
1171/// will also be instantiated and the pointed-to value will be updated with
1172/// the instantiated function type.
1173///
1174/// \param Info if substitution fails for any reason, this object will be
1175/// populated with more information about the failure.
1176///
1177/// \returns TDK_Success if substitution was successful, or some failure
1178/// condition.
1179Sema::TemplateDeductionResult
1180Sema::SubstituteExplicitTemplateArguments(
1181 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001182 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001183 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001184 llvm::SmallVectorImpl<QualType> &ParamTypes,
1185 QualType *FunctionType,
1186 TemplateDeductionInfo &Info) {
1187 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1188 TemplateParameterList *TemplateParams
1189 = FunctionTemplate->getTemplateParameters();
1190
John McCalld5532b62009-11-23 01:53:49 +00001191 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001192 // No arguments to substitute; just copy over the parameter types and
1193 // fill in the function type.
1194 for (FunctionDecl::param_iterator P = Function->param_begin(),
1195 PEnd = Function->param_end();
1196 P != PEnd;
1197 ++P)
1198 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Douglas Gregor83314aa2009-07-08 20:55:45 +00001200 if (FunctionType)
1201 *FunctionType = Function->getType();
1202 return TDK_Success;
1203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Douglas Gregor83314aa2009-07-08 20:55:45 +00001205 // Substitution of the explicit template arguments into a function template
1206 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001207 SFINAETrap Trap(*this);
1208
Douglas Gregor83314aa2009-07-08 20:55:45 +00001209 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001210 // Template arguments that are present shall be specified in the
1211 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001212 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001213 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001214 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
1216 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001217 // explicitly-specified template arguments against this function template,
1218 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001219 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001220 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001221 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1222 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001223 if (Inst)
1224 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Douglas Gregor83314aa2009-07-08 20:55:45 +00001226 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001227 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001228 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001229 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001230 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001231 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001232 if (Index >= TemplateParams->size())
1233 Index = TemplateParams->size() - 1;
1234 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001235 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001236 }
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Douglas Gregor83314aa2009-07-08 20:55:45 +00001238 // Form the template argument list from the explicitly-specified
1239 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001240 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001241 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001242 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
John McCalldf41f182010-10-12 19:40:14 +00001244 // Template argument deduction and the final substitution should be
1245 // done in the context of the templated declaration. Explicit
1246 // argument substitution, on the other hand, needs to happen in the
1247 // calling context.
1248 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1249
Douglas Gregor83314aa2009-07-08 20:55:45 +00001250 // Instantiate the types of each of the function parameters given the
1251 // explicitly-specified template arguments.
1252 for (FunctionDecl::param_iterator P = Function->param_begin(),
1253 PEnd = Function->param_end();
1254 P != PEnd;
1255 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001256 QualType ParamType
1257 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001258 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1259 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001260 if (ParamType.isNull() || Trap.hasErrorOccurred())
1261 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Douglas Gregor83314aa2009-07-08 20:55:45 +00001263 ParamTypes.push_back(ParamType);
1264 }
1265
1266 // If the caller wants a full function type back, instantiate the return
1267 // type and form that function type.
1268 if (FunctionType) {
1269 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001270 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001271 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001272 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001273
1274 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001275 = SubstType(Proto->getResultType(),
1276 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1277 Function->getTypeSpecStartLoc(),
1278 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001279 if (ResultType.isNull() || Trap.hasErrorOccurred())
1280 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001281
1282 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001283 ParamTypes.data(), ParamTypes.size(),
1284 Proto->isVariadic(),
1285 Proto->getTypeQuals(),
1286 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001287 Function->getDeclName(),
1288 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001289 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1290 return TDK_SubstitutionFailure;
1291 }
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Douglas Gregor83314aa2009-07-08 20:55:45 +00001293 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001294 // Trailing template arguments that can be deduced (14.8.2) may be
1295 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001296 // template arguments can be deduced, they may all be omitted; in this
1297 // case, the empty template argument list <> itself may also be omitted.
1298 //
1299 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001300 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001301 Deduced.reserve(TemplateParams->size());
1302 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001303 Deduced.push_back(ExplicitArgumentList->get(I));
1304
Douglas Gregor83314aa2009-07-08 20:55:45 +00001305 return TDK_Success;
1306}
1307
Douglas Gregor02024a92010-03-28 02:42:43 +00001308/// \brief Allocate a TemplateArgumentLoc where all locations have
1309/// been initialized to the given location.
1310///
1311/// \param S The semantic analysis object.
1312///
1313/// \param The template argument we are producing template argument
1314/// location information for.
1315///
1316/// \param NTTPType For a declaration template argument, the type of
1317/// the non-type template parameter that corresponds to this template
1318/// argument.
1319///
1320/// \param Loc The source location to use for the resulting template
1321/// argument.
1322static TemplateArgumentLoc
1323getTrivialTemplateArgumentLoc(Sema &S,
1324 const TemplateArgument &Arg,
1325 QualType NTTPType,
1326 SourceLocation Loc) {
1327 switch (Arg.getKind()) {
1328 case TemplateArgument::Null:
1329 llvm_unreachable("Can't get a NULL template argument here");
1330 break;
1331
1332 case TemplateArgument::Type:
1333 return TemplateArgumentLoc(Arg,
1334 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1335
1336 case TemplateArgument::Declaration: {
1337 Expr *E
1338 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1339 .takeAs<Expr>();
1340 return TemplateArgumentLoc(TemplateArgument(E), E);
1341 }
1342
1343 case TemplateArgument::Integral: {
1344 Expr *E
1345 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1346 return TemplateArgumentLoc(TemplateArgument(E), E);
1347 }
1348
1349 case TemplateArgument::Template:
1350 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1351
1352 case TemplateArgument::Expression:
1353 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1354
1355 case TemplateArgument::Pack:
1356 llvm_unreachable("Template parameter packs are not yet supported");
1357 }
1358
1359 return TemplateArgumentLoc();
1360}
1361
Mike Stump1eb44332009-09-09 15:08:12 +00001362/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001363/// checking the deduced template arguments for completeness and forming
1364/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001365Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001366Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001367 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1368 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001369 FunctionDecl *&Specialization,
1370 TemplateDeductionInfo &Info) {
1371 TemplateParameterList *TemplateParams
1372 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Douglas Gregor83314aa2009-07-08 20:55:45 +00001374 // Template argument deduction for function templates in a SFINAE context.
1375 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 SFINAETrap Trap(*this);
1377
Douglas Gregor83314aa2009-07-08 20:55:45 +00001378 // Enter a new template instantiation context while we instantiate the
1379 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001380 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001381 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001382 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1383 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001384 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001385 return TDK_InstantiationDepth;
1386
John McCall96db3102010-04-29 01:18:58 +00001387 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001388
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001389 // C++ [temp.deduct.type]p2:
1390 // [...] or if any template argument remains neither deduced nor
1391 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001392 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001393 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001394 NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001395 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001396 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001397 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001398 // argument, because it was explicitly-specified. Just record the
1399 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001400 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001401 continue;
1402 }
1403
1404 // We have deduced this argument, so it still needs to be
1405 // checked and converted.
1406
1407 // First, for a non-type template parameter type that is
1408 // initialized by a declaration, we need the type of the
1409 // corresponding non-type template parameter.
1410 QualType NTTPType;
1411 if (NonTypeTemplateParmDecl *NTTP
1412 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1413 if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1414 NTTPType = NTTP->getType();
1415 if (NTTPType->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001416 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1417 Builder.data(), Builder.size());
Douglas Gregor02024a92010-03-28 02:42:43 +00001418 NTTPType = SubstType(NTTPType,
1419 MultiLevelTemplateArgumentList(TemplateArgs),
1420 NTTP->getLocation(),
1421 NTTP->getDeclName());
1422 if (NTTPType.isNull()) {
1423 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001424 // FIXME: These template arguments are temporary. Free them!
1425 Info.reset(TemplateArgumentList::CreateCopy(Context,
1426 Builder.data(),
1427 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001428 return TDK_SubstitutionFailure;
1429 }
1430 }
1431 }
1432 }
1433
1434 // Convert the deduced template argument into a template
1435 // argument that we can check, almost as if the user had written
1436 // the template argument explicitly.
1437 TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1438 Deduced[I],
1439 NTTPType,
Douglas Gregor9b623632010-10-12 23:32:35 +00001440 Info.getLocation());
Douglas Gregor02024a92010-03-28 02:42:43 +00001441
1442 // Check the template argument, converting it as necessary.
1443 if (CheckTemplateArgument(Param, Arg,
1444 FunctionTemplate,
1445 FunctionTemplate->getLocation(),
1446 FunctionTemplate->getSourceRange().getEnd(),
1447 Builder,
1448 Deduced[I].wasDeducedFromArrayBound()
1449 ? CTAK_DeducedFromArrayBound
1450 : CTAK_Deduced)) {
1451 Info.Param = makeTemplateParameter(
1452 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001453 // FIXME: These template arguments are temporary. Free them!
1454 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1455 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001456 return TDK_SubstitutionFailure;
1457 }
1458
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001459 continue;
1460 }
1461
1462 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001463 TemplateArgumentLoc DefArg
1464 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1465 FunctionTemplate->getLocation(),
1466 FunctionTemplate->getSourceRange().getEnd(),
1467 Param,
1468 Builder);
1469
1470 // If there was no default argument, deduction is incomplete.
1471 if (DefArg.getArgument().isNull()) {
1472 Info.Param = makeTemplateParameter(
1473 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1474 return TDK_Incomplete;
1475 }
1476
1477 // Check whether we can actually use the default argument.
1478 if (CheckTemplateArgument(Param, DefArg,
1479 FunctionTemplate,
1480 FunctionTemplate->getLocation(),
1481 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001482 Builder,
1483 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001484 Info.Param = makeTemplateParameter(
1485 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001486 // FIXME: These template arguments are temporary. Free them!
1487 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1488 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001489 return TDK_SubstitutionFailure;
1490 }
1491
1492 // If we get here, we successfully used the default template argument.
1493 }
1494
1495 // Form the template argument list from the deduced template arguments.
1496 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001497 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001498 Info.reset(DeducedArgumentList);
1499
Mike Stump1eb44332009-09-09 15:08:12 +00001500 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001501 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001502 DeclContext *Owner = FunctionTemplate->getDeclContext();
1503 if (FunctionTemplate->getFriendObjectKind())
1504 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001505 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001506 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001507 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001508 if (!Specialization)
1509 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Douglas Gregorf8825742009-09-15 18:26:13 +00001511 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1512 FunctionTemplate->getCanonicalDecl());
1513
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001515 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001516 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1517 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001518 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Douglas Gregor83314aa2009-07-08 20:55:45 +00001520 // There may have been an error that did not prevent us from constructing a
1521 // declaration. Mark the declaration invalid and return with a substitution
1522 // failure.
1523 if (Trap.hasErrorOccurred()) {
1524 Specialization->setInvalidDecl(true);
1525 return TDK_SubstitutionFailure;
1526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Douglas Gregor9b623632010-10-12 23:32:35 +00001528 // If we suppressed any diagnostics while performing template argument
1529 // deduction, and if we haven't already instantiated this declaration,
1530 // keep track of these diagnostics. They'll be emitted if this specialization
1531 // is actually used.
1532 if (Info.diag_begin() != Info.diag_end()) {
1533 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1534 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1535 if (Pos == SuppressedDiagnostics.end())
1536 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1537 .append(Info.diag_begin(), Info.diag_end());
1538 }
1539
Mike Stump1eb44332009-09-09 15:08:12 +00001540 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001541}
1542
John McCall9c72c602010-08-27 09:08:28 +00001543/// Gets the type of a function for template-argument-deducton
1544/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001545static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001546 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001547 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001548 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001549 if (Method->isInstance()) {
1550 // An instance method that's referenced in a form that doesn't
1551 // look like a member pointer is just invalid.
1552 if (!R.HasFormOfMemberPointer) return QualType();
1553
John McCalleff92132010-02-02 02:21:27 +00001554 return Context.getMemberPointerType(Fn->getType(),
1555 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001556 }
1557
1558 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001559 return Context.getPointerType(Fn->getType());
1560}
1561
1562/// Apply the deduction rules for overload sets.
1563///
1564/// \return the null type if this argument should be treated as an
1565/// undeduced context
1566static QualType
1567ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001568 Expr *Arg, QualType ParamType,
1569 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001570
1571 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001572
John McCall9c72c602010-08-27 09:08:28 +00001573 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001574
Douglas Gregor75f21af2010-08-30 21:04:23 +00001575 // C++0x [temp.deduct.call]p4
1576 unsigned TDF = 0;
1577 if (ParamWasReference)
1578 TDF |= TDF_ParamWithReferenceType;
1579 if (R.IsAddressOfOperand)
1580 TDF |= TDF_IgnoreQualifiers;
1581
John McCalleff92132010-02-02 02:21:27 +00001582 // If there were explicit template arguments, we can only find
1583 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1584 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001585 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001586 // But we can still look for an explicit specialization.
1587 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001588 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001589 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001590 return QualType();
1591 }
1592
1593 // C++0x [temp.deduct.call]p6:
1594 // When P is a function type, pointer to function type, or pointer
1595 // to member function type:
1596
1597 if (!ParamType->isFunctionType() &&
1598 !ParamType->isFunctionPointerType() &&
1599 !ParamType->isMemberFunctionPointerType())
1600 return QualType();
1601
1602 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001603 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1604 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001605 NamedDecl *D = (*I)->getUnderlyingDecl();
1606
1607 // - If the argument is an overload set containing one or more
1608 // function templates, the parameter is treated as a
1609 // non-deduced context.
1610 if (isa<FunctionTemplateDecl>(D))
1611 return QualType();
1612
1613 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001614 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1615 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001616
Douglas Gregor75f21af2010-08-30 21:04:23 +00001617 // Function-to-pointer conversion.
1618 if (!ParamWasReference && ParamType->isPointerType() &&
1619 ArgType->isFunctionType())
1620 ArgType = S.Context.getPointerType(ArgType);
1621
John McCalleff92132010-02-02 02:21:27 +00001622 // - If the argument is an overload set (not containing function
1623 // templates), trial argument deduction is attempted using each
1624 // of the members of the set. If deduction succeeds for only one
1625 // of the overload set members, that member is used as the
1626 // argument value for the deduction. If deduction succeeds for
1627 // more than one member of the overload set the parameter is
1628 // treated as a non-deduced context.
1629
1630 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1631 // Type deduction is done independently for each P/A pair, and
1632 // the deduced template argument values are then combined.
1633 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00001634 llvm::SmallVector<DeducedTemplateArgument, 8>
1635 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00001636 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00001637 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001638 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00001639 ParamType, ArgType,
1640 Info, Deduced, TDF);
1641 if (Result) continue;
1642 if (!Match.isNull()) return QualType();
1643 Match = ArgType;
1644 }
1645
1646 return Match;
1647}
1648
Douglas Gregore53060f2009-06-25 22:08:12 +00001649/// \brief Perform template argument deduction from a function call
1650/// (C++ [temp.deduct.call]).
1651///
1652/// \param FunctionTemplate the function template for which we are performing
1653/// template argument deduction.
1654///
Douglas Gregor48026d22010-01-11 18:40:55 +00001655/// \param ExplicitTemplateArguments the explicit template arguments provided
1656/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001657///
Douglas Gregore53060f2009-06-25 22:08:12 +00001658/// \param Args the function call arguments
1659///
1660/// \param NumArgs the number of arguments in Args
1661///
Douglas Gregor48026d22010-01-11 18:40:55 +00001662/// \param Name the name of the function being called. This is only significant
1663/// when the function template is a conversion function template, in which
1664/// case this routine will also perform template argument deduction based on
1665/// the function to which
1666///
Douglas Gregore53060f2009-06-25 22:08:12 +00001667/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001668/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00001669/// template argument deduction.
1670///
1671/// \param Info the argument will be updated to provide additional information
1672/// about template argument deduction.
1673///
1674/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001675Sema::TemplateDeductionResult
1676Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00001677 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001678 Expr **Args, unsigned NumArgs,
1679 FunctionDecl *&Specialization,
1680 TemplateDeductionInfo &Info) {
1681 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001682
Douglas Gregore53060f2009-06-25 22:08:12 +00001683 // C++ [temp.deduct.call]p1:
1684 // Template argument deduction is done by comparing each function template
1685 // parameter type (call it P) with the type of the corresponding argument
1686 // of the call (call it A) as described below.
1687 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001688 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001689 return TDK_TooFewArguments;
1690 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001691 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001692 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00001693 if (!Proto->isVariadic())
1694 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Douglas Gregore53060f2009-06-25 22:08:12 +00001696 CheckArgs = Function->getNumParams();
1697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001699 // The types of the parameters from which we will perform template argument
1700 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00001701 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00001702 TemplateParameterList *TemplateParams
1703 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001704 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001705 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00001706 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00001707 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001708 TemplateDeductionResult Result =
1709 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001710 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001711 Deduced,
1712 ParamTypes,
1713 0,
1714 Info);
1715 if (Result)
1716 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001717
1718 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001719 } else {
1720 // Just fill in the parameter types from the function declaration.
1721 for (unsigned I = 0; I != CheckArgs; ++I)
1722 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001725 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001726 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001727 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001728 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001729 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Douglas Gregor75f21af2010-08-30 21:04:23 +00001731 // C++0x [temp.deduct.call]p3:
1732 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1733 // are ignored for type deduction.
1734 if (ParamType.getCVRQualifiers())
1735 ParamType = ParamType.getLocalUnqualifiedType();
1736 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
1737 if (ParamRefType) {
1738 // [...] If P is a reference type, the type referred to by P is used
1739 // for type deduction.
1740 ParamType = ParamRefType->getPointeeType();
1741 }
1742
John McCalleff92132010-02-02 02:21:27 +00001743 // Overload sets usually make this parameter an undeduced
1744 // context, but there are sometimes special circumstances.
1745 if (ArgType == Context.OverloadTy) {
1746 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001747 Args[I], ParamType,
1748 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00001749 if (ArgType.isNull())
1750 continue;
1751 }
1752
Douglas Gregor75f21af2010-08-30 21:04:23 +00001753 if (ParamRefType) {
1754 // C++0x [temp.deduct.call]p3:
1755 // [...] If P is of the form T&&, where T is a template parameter, and
1756 // the argument is an lvalue, the type A& is used in place of A for
1757 // type deduction.
1758 if (ParamRefType->isRValueReferenceType() &&
1759 ParamRefType->getAs<TemplateTypeParmType>() &&
1760 Args[I]->isLvalue(Context) == Expr::LV_Valid)
1761 ArgType = Context.getLValueReferenceType(ArgType);
1762 } else {
1763 // C++ [temp.deduct.call]p2:
1764 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00001765 // - If A is an array type, the pointer type produced by the
1766 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00001767 // A for type deduction; otherwise,
1768 if (ArgType->isArrayType())
1769 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // - If A is a function type, the pointer type produced by the
1771 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00001772 // of A for type deduction; otherwise,
1773 else if (ArgType->isFunctionType())
1774 ArgType = Context.getPointerType(ArgType);
1775 else {
1776 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1777 // type are ignored for type deduction.
1778 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00001779 if (ArgType.getCVRQualifiers())
1780 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00001781 }
1782 }
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Douglas Gregore53060f2009-06-25 22:08:12 +00001784 // C++0x [temp.deduct.call]p4:
1785 // In general, the deduction process attempts to find template argument
1786 // values that will make the deduced A identical to A (after the type A
1787 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00001788 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor508f1c82009-06-26 23:10:12 +00001790 // - If the original P is a reference type, the deduced A (i.e., the
1791 // type referred to by the reference) can be more cv-qualified than
1792 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00001793 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00001794 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00001795 // - The transformed A can be another pointer or pointer to member
1796 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00001797 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00001798 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
1799 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00001800 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00001801 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00001802 // transformed A can be a derived class of the deduced A. Likewise,
1803 // if P is a pointer to a class of the form simple-template-id, the
1804 // transformed A can be a pointer to a derived class pointed to by
1805 // the deduced A.
1806 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001807 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00001808 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00001809 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00001810 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregore53060f2009-06-25 22:08:12 +00001812 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001813 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00001814 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001815 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00001816 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001818 // FIXME: we need to check that the deduced A is the same as A,
1819 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00001820 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001821
Mike Stump1eb44332009-09-09 15:08:12 +00001822 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00001823 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001824 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00001825}
1826
Douglas Gregor83314aa2009-07-08 20:55:45 +00001827/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00001828/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
1829/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001830///
1831/// \param FunctionTemplate the function template for which we are performing
1832/// template argument deduction.
1833///
Douglas Gregor4b52e252009-12-21 23:17:24 +00001834/// \param ExplicitTemplateArguments the explicitly-specified template
1835/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001836///
1837/// \param ArgFunctionType the function type that will be used as the
1838/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00001839/// function template's function type. This type may be NULL, if there is no
1840/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001841///
1842/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001843/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00001844/// template argument deduction.
1845///
1846/// \param Info the argument will be updated to provide additional information
1847/// about template argument deduction.
1848///
1849/// \returns the result of template argument deduction.
1850Sema::TemplateDeductionResult
1851Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001852 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001853 QualType ArgFunctionType,
1854 FunctionDecl *&Specialization,
1855 TemplateDeductionInfo &Info) {
1856 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1857 TemplateParameterList *TemplateParams
1858 = FunctionTemplate->getTemplateParameters();
1859 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor83314aa2009-07-08 20:55:45 +00001861 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00001862 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001863 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
1864 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001865 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00001866 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001867 if (TemplateDeductionResult Result
1868 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001869 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00001870 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001871 &FunctionType, Info))
1872 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001873
1874 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001875 }
1876
1877 // Template argument deduction for function templates in a SFINAE context.
1878 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001879 SFINAETrap Trap(*this);
1880
John McCalleff92132010-02-02 02:21:27 +00001881 Deduced.resize(TemplateParams->size());
1882
Douglas Gregor4b52e252009-12-21 23:17:24 +00001883 if (!ArgFunctionType.isNull()) {
1884 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00001885 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001886 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00001887 FunctionType, ArgFunctionType, Info,
1888 Deduced, 0))
1889 return Result;
1890 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00001891
1892 if (TemplateDeductionResult Result
1893 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1894 NumExplicitlySpecified,
1895 Specialization, Info))
1896 return Result;
1897
1898 // If the requested function type does not match the actual type of the
1899 // specialization, template argument deduction fails.
1900 if (!ArgFunctionType.isNull() &&
1901 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
1902 return TDK_NonDeducedMismatch;
1903
1904 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001905}
1906
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001907/// \brief Deduce template arguments for a templated conversion
1908/// function (C++ [temp.deduct.conv]) and, if successful, produce a
1909/// conversion function template specialization.
1910Sema::TemplateDeductionResult
1911Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1912 QualType ToType,
1913 CXXConversionDecl *&Specialization,
1914 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00001915 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001916 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
1917 QualType FromType = Conv->getConversionType();
1918
1919 // Canonicalize the types for deduction.
1920 QualType P = Context.getCanonicalType(FromType);
1921 QualType A = Context.getCanonicalType(ToType);
1922
1923 // C++0x [temp.deduct.conv]p3:
1924 // If P is a reference type, the type referred to by P is used for
1925 // type deduction.
1926 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
1927 P = PRef->getPointeeType();
1928
1929 // C++0x [temp.deduct.conv]p3:
1930 // If A is a reference type, the type referred to by A is used
1931 // for type deduction.
1932 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
1933 A = ARef->getPointeeType();
1934 // C++ [temp.deduct.conv]p2:
1935 //
Mike Stump1eb44332009-09-09 15:08:12 +00001936 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001937 else {
1938 assert(!A->isReferenceType() && "Reference types were handled above");
1939
1940 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00001941 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001942 // of P for type deduction; otherwise,
1943 if (P->isArrayType())
1944 P = Context.getArrayDecayedType(P);
1945 // - If P is a function type, the pointer type produced by the
1946 // function-to-pointer standard conversion (4.3) is used in
1947 // place of P for type deduction; otherwise,
1948 else if (P->isFunctionType())
1949 P = Context.getPointerType(P);
1950 // - If P is a cv-qualified type, the top level cv-qualifiers of
1951 // P’s type are ignored for type deduction.
1952 else
1953 P = P.getUnqualifiedType();
1954
1955 // C++0x [temp.deduct.conv]p3:
1956 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
1957 // type are ignored for type deduction.
1958 A = A.getUnqualifiedType();
1959 }
1960
1961 // Template argument deduction for function templates in a SFINAE context.
1962 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001963 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001964
1965 // C++ [temp.deduct.conv]p1:
1966 // Template argument deduction is done by comparing the return
1967 // type of the template conversion function (call it P) with the
1968 // type that is required as the result of the conversion (call it
1969 // A) as described in 14.8.2.4.
1970 TemplateParameterList *TemplateParams
1971 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001972 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00001973 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001974
1975 // C++0x [temp.deduct.conv]p4:
1976 // In general, the deduction process attempts to find template
1977 // argument values that will make the deduced A identical to
1978 // A. However, there are two cases that allow a difference:
1979 unsigned TDF = 0;
1980 // - If the original A is a reference type, A can be more
1981 // cv-qualified than the deduced A (i.e., the type referred to
1982 // by the reference)
1983 if (ToType->isReferenceType())
1984 TDF |= TDF_ParamWithReferenceType;
1985 // - The deduced A can be another pointer or pointer to member
1986 // type that can be converted to A via a qualification
1987 // conversion.
1988 //
1989 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
1990 // both P and A are pointers or member pointers. In this case, we
1991 // just ignore cv-qualifiers completely).
1992 if ((P->isPointerType() && A->isPointerType()) ||
1993 (P->isMemberPointerType() && P->isMemberPointerType()))
1994 TDF |= TDF_IgnoreQualifiers;
1995 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001996 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001997 P, A, Info, Deduced, TDF))
1998 return Result;
1999
2000 // FIXME: we need to check that the deduced A is the same as A,
2001 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002003 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002004 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002005 FunctionDecl *Spec = 0;
2006 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002007 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2008 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002009 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2010 return Result;
2011}
2012
Douglas Gregor4b52e252009-12-21 23:17:24 +00002013/// \brief Deduce template arguments for a function template when there is
2014/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2015///
2016/// \param FunctionTemplate the function template for which we are performing
2017/// template argument deduction.
2018///
2019/// \param ExplicitTemplateArguments the explicitly-specified template
2020/// arguments.
2021///
2022/// \param Specialization if template argument deduction was successful,
2023/// this will be set to the function template specialization produced by
2024/// template argument deduction.
2025///
2026/// \param Info the argument will be updated to provide additional information
2027/// about template argument deduction.
2028///
2029/// \returns the result of template argument deduction.
2030Sema::TemplateDeductionResult
2031Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2032 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2033 FunctionDecl *&Specialization,
2034 TemplateDeductionInfo &Info) {
2035 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2036 QualType(), Specialization, Info);
2037}
2038
Douglas Gregor8a514912009-09-14 18:39:43 +00002039/// \brief Stores the result of comparing the qualifiers of two types.
2040enum DeductionQualifierComparison {
2041 NeitherMoreQualified = 0,
2042 ParamMoreQualified,
2043 ArgMoreQualified
2044};
2045
2046/// \brief Deduce the template arguments during partial ordering by comparing
2047/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2048///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002049/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002050///
2051/// \param TemplateParams the template parameters that we are deducing
2052///
2053/// \param ParamIn the parameter type
2054///
2055/// \param ArgIn the argument type
2056///
2057/// \param Info information about the template argument deduction itself
2058///
2059/// \param Deduced the deduced template arguments
2060///
2061/// \returns the result of template argument deduction so far. Note that a
2062/// "success" result means that template argument deduction has not yet failed,
2063/// but it may still fail, later, for other reasons.
2064static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002065DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002066 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002067 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002068 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002069 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2070 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002071 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2072 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002073
2074 // C++0x [temp.deduct.partial]p5:
2075 // Before the partial ordering is done, certain transformations are
2076 // performed on the types used for partial ordering:
2077 // - If P is a reference type, P is replaced by the type referred to.
2078 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002079 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002080 Param = ParamRef->getPointeeType();
2081
2082 // - If A is a reference type, A is replaced by the type referred to.
2083 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002084 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002085 Arg = ArgRef->getPointeeType();
2086
John McCalle27ec8a2009-10-23 23:03:21 +00002087 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002088 // C++0x [temp.deduct.partial]p6:
2089 // If both P and A were reference types (before being replaced with the
2090 // type referred to above), determine which of the two types (if any) is
2091 // more cv-qualified than the other; otherwise the types are considered to
2092 // be equally cv-qualified for partial ordering purposes. The result of this
2093 // determination will be used below.
2094 //
2095 // We save this information for later, using it only when deduction
2096 // succeeds in both directions.
2097 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2098 if (Param.isMoreQualifiedThan(Arg))
2099 QualifierResult = ParamMoreQualified;
2100 else if (Arg.isMoreQualifiedThan(Param))
2101 QualifierResult = ArgMoreQualified;
2102 QualifierComparisons->push_back(QualifierResult);
2103 }
2104
2105 // C++0x [temp.deduct.partial]p7:
2106 // Remove any top-level cv-qualifiers:
2107 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2108 // version of P.
2109 Param = Param.getUnqualifiedType();
2110 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2111 // version of A.
2112 Arg = Arg.getUnqualifiedType();
2113
2114 // C++0x [temp.deduct.partial]p8:
2115 // Using the resulting types P and A the deduction is then done as
2116 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2117 // from the argument template is considered to be at least as specialized
2118 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002119 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002120 Deduced, TDF_None);
2121}
2122
2123static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002124MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2125 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002126 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002127 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002128
2129/// \brief If this is a non-static member function,
2130static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2131 CXXMethodDecl *Method,
2132 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2133 if (Method->isStatic())
2134 return;
2135
2136 // C++ [over.match.funcs]p4:
2137 //
2138 // For non-static member functions, the type of the implicit
2139 // object parameter is
2140 // — "lvalue reference to cv X" for functions declared without a
2141 // ref-qualifier or with the & ref-qualifier
2142 // - "rvalue reference to cv X" for functions declared with the
2143 // && ref-qualifier
2144 //
2145 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2146 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2147 ArgTy = Context.getQualifiedType(ArgTy,
2148 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2149 ArgTy = Context.getLValueReferenceType(ArgTy);
2150 ArgTypes.push_back(ArgTy);
2151}
2152
Douglas Gregor8a514912009-09-14 18:39:43 +00002153/// \brief Determine whether the function template \p FT1 is at least as
2154/// specialized as \p FT2.
2155static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002156 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002157 FunctionTemplateDecl *FT1,
2158 FunctionTemplateDecl *FT2,
2159 TemplatePartialOrderingContext TPOC,
2160 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2161 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2162 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2163 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2164 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2165
2166 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2167 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002168 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002169 Deduced.resize(TemplateParams->size());
2170
2171 // C++0x [temp.deduct.partial]p3:
2172 // The types used to determine the ordering depend on the context in which
2173 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002174 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8a514912009-09-14 18:39:43 +00002175 switch (TPOC) {
2176 case TPOC_Call: {
2177 // - In the context of a function call, the function parameter types are
2178 // used.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002179 llvm::SmallVector<QualType, 4> Args1;
2180 if (CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1))
2181 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2182 Args1.insert(Args1.end(),
2183 Proto1->arg_type_begin(), Proto1->arg_type_end());
2184
2185 llvm::SmallVector<QualType, 4> Args2;
2186 if (CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2))
2187 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2188 Args2.insert(Args2.end(),
2189 Proto2->arg_type_begin(), Proto2->arg_type_end());
2190
2191 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002192 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002193 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002194 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002195 Args2[I],
2196 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002197 Info,
2198 Deduced,
2199 QualifierComparisons))
2200 return false;
2201
2202 break;
2203 }
2204
2205 case TPOC_Conversion:
2206 // - In the context of a call to a conversion operator, the return types
2207 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002208 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002209 TemplateParams,
2210 Proto2->getResultType(),
2211 Proto1->getResultType(),
2212 Info,
2213 Deduced,
2214 QualifierComparisons))
2215 return false;
2216 break;
2217
2218 case TPOC_Other:
2219 // - In other contexts (14.6.6.2) the function template’s function type
2220 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002221 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002222 TemplateParams,
2223 FD2->getType(),
2224 FD1->getType(),
2225 Info,
2226 Deduced,
2227 QualifierComparisons))
2228 return false;
2229 break;
2230 }
2231
2232 // C++0x [temp.deduct.partial]p11:
2233 // In most cases, all template parameters must have values in order for
2234 // deduction to succeed, but for partial ordering purposes a template
2235 // parameter may remain without a value provided it is not used in the
2236 // types being used for partial ordering. [ Note: a template parameter used
2237 // in a non-deduced context is considered used. -end note]
2238 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2239 for (; ArgIdx != NumArgs; ++ArgIdx)
2240 if (Deduced[ArgIdx].isNull())
2241 break;
2242
2243 if (ArgIdx == NumArgs) {
2244 // All template arguments were deduced. FT1 is at least as specialized
2245 // as FT2.
2246 return true;
2247 }
2248
Douglas Gregore73bb602009-09-14 21:25:05 +00002249 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002250 llvm::SmallVector<bool, 4> UsedParameters;
2251 UsedParameters.resize(TemplateParams->size());
2252 switch (TPOC) {
2253 case TPOC_Call: {
2254 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
2255 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002256 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2257 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002258 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002259 break;
2260 }
2261
2262 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002263 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2264 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002265 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002266 break;
2267
2268 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002269 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2270 TemplateParams->getDepth(),
2271 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002272 break;
2273 }
2274
2275 for (; ArgIdx != NumArgs; ++ArgIdx)
2276 // If this argument had no value deduced but was used in one of the types
2277 // used for partial ordering, then deduction fails.
2278 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2279 return false;
2280
2281 return true;
2282}
2283
2284
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002285/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002286/// to the rules of function template partial ordering (C++ [temp.func.order]).
2287///
2288/// \param FT1 the first function template
2289///
2290/// \param FT2 the second function template
2291///
Douglas Gregor8a514912009-09-14 18:39:43 +00002292/// \param TPOC the context in which we are performing partial ordering of
2293/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002294///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002295/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002296/// template is more specialized, returns NULL.
2297FunctionTemplateDecl *
2298Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2299 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002300 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002301 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002302 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002303 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2304 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002305 &QualifierComparisons);
2306
2307 if (Better1 != Better2) // We have a clear winner
2308 return Better1? FT1 : FT2;
2309
2310 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002311 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002312
2313
2314 // C++0x [temp.deduct.partial]p10:
2315 // If for each type being considered a given template is at least as
2316 // specialized for all types and more specialized for some set of types and
2317 // the other template is not more specialized for any types or is not at
2318 // least as specialized for any types, then the given template is more
2319 // specialized than the other template. Otherwise, neither template is more
2320 // specialized than the other.
2321 Better1 = false;
2322 Better2 = false;
2323 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2324 // C++0x [temp.deduct.partial]p9:
2325 // If, for a given type, deduction succeeds in both directions (i.e., the
2326 // types are identical after the transformations above) and if the type
2327 // from the argument template is more cv-qualified than the type from the
2328 // parameter template (as described above) that type is considered to be
2329 // more specialized than the other. If neither type is more cv-qualified
2330 // than the other then neither type is more specialized than the other.
2331 switch (QualifierComparisons[I]) {
2332 case NeitherMoreQualified:
2333 break;
2334
2335 case ParamMoreQualified:
2336 Better1 = true;
2337 if (Better2)
2338 return 0;
2339 break;
2340
2341 case ArgMoreQualified:
2342 Better2 = true;
2343 if (Better1)
2344 return 0;
2345 break;
2346 }
2347 }
2348
2349 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002350 if (Better1)
2351 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002352 else if (Better2)
2353 return FT2;
2354 else
2355 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002356}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002357
Douglas Gregord5a423b2009-09-25 18:43:00 +00002358/// \brief Determine if the two templates are equivalent.
2359static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2360 if (T1 == T2)
2361 return true;
2362
2363 if (!T1 || !T2)
2364 return false;
2365
2366 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2367}
2368
2369/// \brief Retrieve the most specialized of the given function template
2370/// specializations.
2371///
John McCallc373d482010-01-27 01:50:18 +00002372/// \param SpecBegin the start iterator of the function template
2373/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002374///
John McCallc373d482010-01-27 01:50:18 +00002375/// \param SpecEnd the end iterator of the function template
2376/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002377///
2378/// \param TPOC the partial ordering context to use to compare the function
2379/// template specializations.
2380///
2381/// \param Loc the location where the ambiguity or no-specializations
2382/// diagnostic should occur.
2383///
2384/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2385/// no matching candidates.
2386///
2387/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2388/// occurs.
2389///
2390/// \param CandidateDiag partial diagnostic used for each function template
2391/// specialization that is a candidate in the ambiguous ordering. One parameter
2392/// in this diagnostic should be unbound, which will correspond to the string
2393/// describing the template arguments for the function template specialization.
2394///
2395/// \param Index if non-NULL and the result of this function is non-nULL,
2396/// receives the index corresponding to the resulting function template
2397/// specialization.
2398///
2399/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002400/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002401///
2402/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2403/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002404UnresolvedSetIterator
2405Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2406 UnresolvedSetIterator SpecEnd,
2407 TemplatePartialOrderingContext TPOC,
2408 SourceLocation Loc,
2409 const PartialDiagnostic &NoneDiag,
2410 const PartialDiagnostic &AmbigDiag,
2411 const PartialDiagnostic &CandidateDiag) {
2412 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002413 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002414 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002415 }
2416
John McCallc373d482010-01-27 01:50:18 +00002417 if (SpecBegin + 1 == SpecEnd)
2418 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002419
2420 // Find the function template that is better than all of the templates it
2421 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002422 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002423 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002424 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002425 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002426 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2427 FunctionTemplateDecl *Challenger
2428 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002429 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002430 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002431 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002432 Challenger)) {
2433 Best = I;
2434 BestTemplate = Challenger;
2435 }
2436 }
2437
2438 // Make sure that the "best" function template is more specialized than all
2439 // of the others.
2440 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002441 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2442 FunctionTemplateDecl *Challenger
2443 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002444 if (I != Best &&
2445 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002446 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002447 BestTemplate)) {
2448 Ambiguous = true;
2449 break;
2450 }
2451 }
2452
2453 if (!Ambiguous) {
2454 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002455 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002456 }
2457
2458 // Diagnose the ambiguity.
2459 Diag(Loc, AmbigDiag);
2460
2461 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002462 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2463 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002464 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002465 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2466 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002467
John McCallc373d482010-01-27 01:50:18 +00002468 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002469}
2470
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002471/// \brief Returns the more specialized class template partial specialization
2472/// according to the rules of partial ordering of class template partial
2473/// specializations (C++ [temp.class.order]).
2474///
2475/// \param PS1 the first class template partial specialization
2476///
2477/// \param PS2 the second class template partial specialization
2478///
2479/// \returns the more specialized class template partial specialization. If
2480/// neither partial specialization is more specialized, returns NULL.
2481ClassTemplatePartialSpecializationDecl *
2482Sema::getMoreSpecializedPartialSpecialization(
2483 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002484 ClassTemplatePartialSpecializationDecl *PS2,
2485 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002486 // C++ [temp.class.order]p1:
2487 // For two class template partial specializations, the first is at least as
2488 // specialized as the second if, given the following rewrite to two
2489 // function templates, the first function template is at least as
2490 // specialized as the second according to the ordering rules for function
2491 // templates (14.6.6.2):
2492 // - the first function template has the same template parameters as the
2493 // first partial specialization and has a single function parameter
2494 // whose type is a class template specialization with the template
2495 // arguments of the first partial specialization, and
2496 // - the second function template has the same template parameters as the
2497 // second partial specialization and has a single function parameter
2498 // whose type is a class template specialization with the template
2499 // arguments of the second partial specialization.
2500 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002501 // Rather than synthesize function templates, we merely perform the
2502 // equivalent partial ordering by performing deduction directly on
2503 // the template arguments of the class template partial
2504 // specializations. This computation is slightly simpler than the
2505 // general problem of function template partial ordering, because
2506 // class template partial specializations are more constrained. We
2507 // know that every template parameter is deducible from the class
2508 // template partial specialization's template arguments, for
2509 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002510 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002511 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002512
2513 QualType PT1 = PS1->getInjectedSpecializationType();
2514 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002515
2516 // Determine whether PS1 is at least as specialized as PS2
2517 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002518 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002519 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002520 PT2,
2521 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002522 Info,
2523 Deduced,
2524 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002525 if (Better1) {
2526 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2527 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002528 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2529 PS1->getTemplateArgs(),
2530 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002531 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002532
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002533 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002534 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002535 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002536 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002537 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002538 PT1,
2539 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002540 Info,
2541 Deduced,
2542 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002543 if (Better2) {
2544 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2545 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002546 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2547 PS2->getTemplateArgs(),
2548 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002549 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002550
2551 if (Better1 == Better2)
2552 return 0;
2553
2554 return Better1? PS1 : PS2;
2555}
2556
Mike Stump1eb44332009-09-09 15:08:12 +00002557static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002558MarkUsedTemplateParameters(Sema &SemaRef,
2559 const TemplateArgument &TemplateArg,
2560 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002561 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002562 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002563
Douglas Gregore73bb602009-09-14 21:25:05 +00002564/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002565/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002566static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002567MarkUsedTemplateParameters(Sema &SemaRef,
2568 const Expr *E,
2569 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002570 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002571 llvm::SmallVectorImpl<bool> &Used) {
2572 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2573 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002574 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002575 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002576 return;
2577
Mike Stump1eb44332009-09-09 15:08:12 +00002578 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002579 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2580 if (!NTTP)
2581 return;
2582
Douglas Gregored9c0f92009-10-29 00:04:11 +00002583 if (NTTP->getDepth() == Depth)
2584 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002585}
2586
Douglas Gregore73bb602009-09-14 21:25:05 +00002587/// \brief Mark the template parameters that are used by the given
2588/// nested name specifier.
2589static void
2590MarkUsedTemplateParameters(Sema &SemaRef,
2591 NestedNameSpecifier *NNS,
2592 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002593 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002594 llvm::SmallVectorImpl<bool> &Used) {
2595 if (!NNS)
2596 return;
2597
Douglas Gregored9c0f92009-10-29 00:04:11 +00002598 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2599 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002600 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002601 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002602}
2603
2604/// \brief Mark the template parameters that are used by the given
2605/// template name.
2606static void
2607MarkUsedTemplateParameters(Sema &SemaRef,
2608 TemplateName Name,
2609 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002610 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002611 llvm::SmallVectorImpl<bool> &Used) {
2612 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2613 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00002614 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2615 if (TTP->getDepth() == Depth)
2616 Used[TTP->getIndex()] = true;
2617 }
Douglas Gregore73bb602009-09-14 21:25:05 +00002618 return;
2619 }
2620
Douglas Gregor788cd062009-11-11 01:00:40 +00002621 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2622 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2623 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002624 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00002625 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2626 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002627}
2628
2629/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002630/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002631static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002632MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2633 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002634 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002635 llvm::SmallVectorImpl<bool> &Used) {
2636 if (T.isNull())
2637 return;
2638
Douglas Gregor031a5882009-06-13 00:26:55 +00002639 // Non-dependent types have nothing deducible
2640 if (!T->isDependentType())
2641 return;
2642
2643 T = SemaRef.Context.getCanonicalType(T);
2644 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002645 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002646 MarkUsedTemplateParameters(SemaRef,
2647 cast<PointerType>(T)->getPointeeType(),
2648 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002649 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002650 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002651 break;
2652
2653 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002654 MarkUsedTemplateParameters(SemaRef,
2655 cast<BlockPointerType>(T)->getPointeeType(),
2656 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002657 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002658 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002659 break;
2660
2661 case Type::LValueReference:
2662 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00002663 MarkUsedTemplateParameters(SemaRef,
2664 cast<ReferenceType>(T)->getPointeeType(),
2665 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002666 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002667 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002668 break;
2669
2670 case Type::MemberPointer: {
2671 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00002672 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002673 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002674 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002675 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002676 break;
2677 }
2678
2679 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002680 MarkUsedTemplateParameters(SemaRef,
2681 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002682 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002683 // Fall through to check the element type
2684
2685 case Type::ConstantArray:
2686 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002687 MarkUsedTemplateParameters(SemaRef,
2688 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002689 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002690 break;
2691
2692 case Type::Vector:
2693 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00002694 MarkUsedTemplateParameters(SemaRef,
2695 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002696 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002697 break;
2698
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002699 case Type::DependentSizedExtVector: {
2700 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002701 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002702 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002703 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002704 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002705 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002706 break;
2707 }
2708
Douglas Gregor031a5882009-06-13 00:26:55 +00002709 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002710 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002711 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002712 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002713 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00002714 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002715 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002716 break;
2717 }
2718
Douglas Gregored9c0f92009-10-29 00:04:11 +00002719 case Type::TemplateTypeParm: {
2720 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
2721 if (TTP->getDepth() == Depth)
2722 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002723 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002724 }
Douglas Gregor031a5882009-06-13 00:26:55 +00002725
John McCall31f17ec2010-04-27 00:57:59 +00002726 case Type::InjectedClassName:
2727 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2728 // fall through
2729
Douglas Gregor031a5882009-06-13 00:26:55 +00002730 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00002731 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002732 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002733 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002734 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002735 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002736 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2737 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002738 break;
2739 }
2740
Douglas Gregore73bb602009-09-14 21:25:05 +00002741 case Type::Complex:
2742 if (!OnlyDeduced)
2743 MarkUsedTemplateParameters(SemaRef,
2744 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002745 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002746 break;
2747
Douglas Gregor4714c122010-03-31 17:34:00 +00002748 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00002749 if (!OnlyDeduced)
2750 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00002751 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002752 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002753 break;
2754
John McCall33500952010-06-11 00:33:02 +00002755 case Type::DependentTemplateSpecialization: {
2756 const DependentTemplateSpecializationType *Spec
2757 = cast<DependentTemplateSpecializationType>(T);
2758 if (!OnlyDeduced)
2759 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
2760 OnlyDeduced, Depth, Used);
2761 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2762 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2763 Used);
2764 break;
2765 }
2766
John McCallad5e7382010-03-01 23:49:17 +00002767 case Type::TypeOf:
2768 if (!OnlyDeduced)
2769 MarkUsedTemplateParameters(SemaRef,
2770 cast<TypeOfType>(T)->getUnderlyingType(),
2771 OnlyDeduced, Depth, Used);
2772 break;
2773
2774 case Type::TypeOfExpr:
2775 if (!OnlyDeduced)
2776 MarkUsedTemplateParameters(SemaRef,
2777 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
2778 OnlyDeduced, Depth, Used);
2779 break;
2780
2781 case Type::Decltype:
2782 if (!OnlyDeduced)
2783 MarkUsedTemplateParameters(SemaRef,
2784 cast<DecltypeType>(T)->getUnderlyingExpr(),
2785 OnlyDeduced, Depth, Used);
2786 break;
2787
Douglas Gregore73bb602009-09-14 21:25:05 +00002788 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00002789 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00002790 case Type::VariableArray:
2791 case Type::FunctionNoProto:
2792 case Type::Record:
2793 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00002794 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00002795 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002796 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00002797 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00002798#define TYPE(Class, Base)
2799#define ABSTRACT_TYPE(Class, Base)
2800#define DEPENDENT_TYPE(Class, Base)
2801#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2802#include "clang/AST/TypeNodes.def"
2803 break;
2804 }
2805}
2806
Douglas Gregore73bb602009-09-14 21:25:05 +00002807/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00002808/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00002809static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002810MarkUsedTemplateParameters(Sema &SemaRef,
2811 const TemplateArgument &TemplateArg,
2812 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002813 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002814 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002815 switch (TemplateArg.getKind()) {
2816 case TemplateArgument::Null:
2817 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00002818 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00002819 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Douglas Gregor031a5882009-06-13 00:26:55 +00002821 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00002822 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002823 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002824 break;
2825
Douglas Gregor788cd062009-11-11 01:00:40 +00002826 case TemplateArgument::Template:
2827 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
2828 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002829 break;
2830
2831 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00002832 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002833 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002834 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00002835
Anders Carlssond01b1da2009-06-15 17:04:53 +00002836 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00002837 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
2838 PEnd = TemplateArg.pack_end();
2839 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002840 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00002841 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00002842 }
2843}
2844
2845/// \brief Mark the template parameters can be deduced by the given
2846/// template argument list.
2847///
2848/// \param TemplateArgs the template argument list from which template
2849/// parameters will be deduced.
2850///
2851/// \param Deduced a bit vector whose elements will be set to \c true
2852/// to indicate when the corresponding template parameter will be
2853/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00002854void
Douglas Gregore73bb602009-09-14 21:25:05 +00002855Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002856 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002857 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002858 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002859 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
2860 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002861}
Douglas Gregor63f07c52009-09-18 23:21:38 +00002862
2863/// \brief Marks all of the template parameters that will be deduced by a
2864/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00002865void
2866Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
2867 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00002868 TemplateParameterList *TemplateParams
2869 = FunctionTemplate->getTemplateParameters();
2870 Deduced.clear();
2871 Deduced.resize(TemplateParams->size());
2872
2873 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2874 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2875 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002876 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00002877}