blob: d5a036d4fb942271121b9cae77acdbeef88a39de [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument *Params, unsigned NumParams,
91 const TemplateArgument *Args, unsigned NumArgs,
92 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000093 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +000095
Douglas Gregor199d9912009-06-05 00:53:49 +000096/// \brief If the given expression is of a form that permits the deduction
97/// of a non-type template parameter, return the declaration of that
98/// non-type template parameter.
99static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
100 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
101 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Douglas Gregor199d9912009-06-05 00:53:49 +0000103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
104 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Douglas Gregor199d9912009-06-05 00:53:49 +0000106 return 0;
107}
108
Mike Stump1eb44332009-09-09 15:08:12 +0000109/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000110/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000111static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000112DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000113 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000114 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000115 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000116 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000117 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000118 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000119 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Douglas Gregor199d9912009-06-05 00:53:49 +0000121 if (Deduced[NTTP->getIndex()].isNull()) {
Douglas Gregor02024a92010-03-28 02:42:43 +0000122 Deduced[NTTP->getIndex()] = DeducedTemplateArgument(Value, ValueType,
123 DeducedFromArrayBound);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000124 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000125 }
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000127 if (Deduced[NTTP->getIndex()].getKind() != TemplateArgument::Integral) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000128 Info.Param = NTTP;
129 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000130 Info.SecondArg = TemplateArgument(Value, ValueType);
131 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000132 }
133
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000134 // Extent the smaller of the two values.
135 llvm::APSInt PrevValue = *Deduced[NTTP->getIndex()].getAsIntegral();
136 if (!hasSameExtendedValue(PrevValue, Value)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000137 Info.Param = NTTP;
138 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000139 Info.SecondArg = TemplateArgument(Value, ValueType);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000140 return Sema::TDK_Inconsistent;
141 }
142
Douglas Gregor02024a92010-03-28 02:42:43 +0000143 if (!DeducedFromArrayBound)
144 Deduced[NTTP->getIndex()].setDeducedFromArrayBound(false);
145
Douglas Gregorf67875d2009-06-12 18:26:56 +0000146 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000147}
148
Mike Stump1eb44332009-09-09 15:08:12 +0000149/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000150/// from the given type- or value-dependent expression.
151///
152/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000153static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000154DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000155 NonTypeTemplateParmDecl *NTTP,
156 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000157 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000158 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000159 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000160 "Cannot deduce non-type template argument with depth > 0");
161 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
162 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Douglas Gregor199d9912009-06-05 00:53:49 +0000164 if (Deduced[NTTP->getIndex()].isNull()) {
John McCall3fa5cae2010-10-26 07:05:15 +0000165 Deduced[NTTP->getIndex()] = TemplateArgument(Value);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000166 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Douglas Gregor199d9912009-06-05 00:53:49 +0000169 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
Mike Stump1eb44332009-09-09 15:08:12 +0000170 // Okay, we deduced a constant in one case and a dependent expression
171 // in another case. FIXME: Later, we will check that instantiating the
Douglas Gregor199d9912009-06-05 00:53:49 +0000172 // dependent expression gives us the constant value.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000173 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000174 }
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000176 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
177 // Compare the expressions for equality
178 llvm::FoldingSetNodeID ID1, ID2;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000179 Deduced[NTTP->getIndex()].getAsExpr()->Profile(ID1, S.Context, true);
180 Value->Profile(ID2, S.Context, true);
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000181 if (ID1 == ID2)
182 return Sema::TDK_Success;
183
184 // FIXME: Fill in argument mismatch information
185 return Sema::TDK_NonDeducedMismatch;
186 }
187
Douglas Gregorf67875d2009-06-12 18:26:56 +0000188 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000189}
190
Douglas Gregor15755cb2009-11-13 23:45:44 +0000191/// \brief Deduce the value of the given non-type template parameter
192/// from the given declaration.
193///
194/// \returns true if deduction succeeded, false otherwise.
195static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000196DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000197 NonTypeTemplateParmDecl *NTTP,
198 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000199 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000200 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000201 assert(NTTP->getDepth() == 0 &&
202 "Cannot deduce non-type template argument with depth > 0");
203
204 if (Deduced[NTTP->getIndex()].isNull()) {
205 Deduced[NTTP->getIndex()] = TemplateArgument(D->getCanonicalDecl());
206 return Sema::TDK_Success;
207 }
208
209 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
210 // Okay, we deduced a declaration in one case and a dependent expression
211 // in another case.
212 return Sema::TDK_Success;
213 }
214
215 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Declaration) {
216 // Compare the declarations for equality
217 if (Deduced[NTTP->getIndex()].getAsDecl()->getCanonicalDecl() ==
218 D->getCanonicalDecl())
219 return Sema::TDK_Success;
220
221 // FIXME: Fill in argument mismatch information
222 return Sema::TDK_NonDeducedMismatch;
223 }
224
225 return Sema::TDK_Success;
226}
227
Douglas Gregorf67875d2009-06-12 18:26:56 +0000228static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000229DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000230 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000231 TemplateName Param,
232 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000233 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000234 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000235 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000236 if (!ParamDecl) {
237 // The parameter type is dependent and is not a template template parameter,
238 // so there is nothing that we can deduce.
239 return Sema::TDK_Success;
240 }
241
242 if (TemplateTemplateParmDecl *TempParam
243 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
244 // Bind the template template parameter to the given template name.
245 TemplateArgument &ExistingArg = Deduced[TempParam->getIndex()];
246 if (ExistingArg.isNull()) {
247 // This is the first deduction for this template template parameter.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000248 ExistingArg = TemplateArgument(S.Context.getCanonicalTemplateName(Arg));
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000249 return Sema::TDK_Success;
250 }
251
252 // Verify that the previous binding matches this deduction.
253 assert(ExistingArg.getKind() == TemplateArgument::Template);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000254 if (S.Context.hasSameTemplateName(ExistingArg.getAsTemplate(), Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000255 return Sema::TDK_Success;
256
257 // Inconsistent deduction.
258 Info.Param = TempParam;
259 Info.FirstArg = ExistingArg;
260 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000261 return Sema::TDK_Inconsistent;
262 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000263
264 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000265 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000266 return Sema::TDK_Success;
267
268 // Mismatch of non-dependent template parameter to argument.
269 Info.FirstArg = TemplateArgument(Param);
270 Info.SecondArg = TemplateArgument(Arg);
271 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000272}
273
Mike Stump1eb44332009-09-09 15:08:12 +0000274/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000275/// type (which is a template-id) with the template argument type.
276///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000277/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000278///
279/// \param TemplateParams the template parameters that we are deducing
280///
281/// \param Param the parameter type
282///
283/// \param Arg the argument type
284///
285/// \param Info information about the template argument deduction itself
286///
287/// \param Deduced the deduced template arguments
288///
289/// \returns the result of template argument deduction so far. Note that a
290/// "success" result means that template argument deduction has not yet failed,
291/// but it may still fail, later, for other reasons.
292static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000293DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000294 TemplateParameterList *TemplateParams,
295 const TemplateSpecializationType *Param,
296 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000297 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000298 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000299 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000301 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000302 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000303 = dyn_cast<TemplateSpecializationType>(Arg)) {
304 // Perform template argument deduction for the template name.
305 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000306 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000307 Param->getTemplateName(),
308 SpecArg->getTemplateName(),
309 Info, Deduced))
310 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000313 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000314 // argument. Ignore any missing/extra arguments, since they could be
315 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000316 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000317 Param->getArgs(), Param->getNumArgs(),
318 SpecArg->getArgs(), SpecArg->getNumArgs(),
319 Info, Deduced,
320 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000321 }
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000323 // If the argument type is a class template specialization, we
324 // perform template argument deduction using its template
325 // arguments.
326 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
327 if (!RecordArg)
328 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
330 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000331 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
332 if (!SpecArg)
333 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000335 // Perform template argument deduction for the template name.
336 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000337 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000338 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000339 Param->getTemplateName(),
340 TemplateName(SpecArg->getSpecializedTemplate()),
341 Info, Deduced))
342 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Douglas Gregor20a55e22010-12-22 18:17:10 +0000344 // Perform template argument deduction for the template arguments.
345 return DeduceTemplateArguments(S, TemplateParams,
346 Param->getArgs(), Param->getNumArgs(),
347 SpecArg->getTemplateArgs().data(),
348 SpecArg->getTemplateArgs().size(),
349 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000350}
351
John McCallcd05e812010-08-28 22:14:41 +0000352/// \brief Determines whether the given type is an opaque type that
353/// might be more qualified when instantiated.
354static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
355 switch (T->getTypeClass()) {
356 case Type::TypeOfExpr:
357 case Type::TypeOf:
358 case Type::DependentName:
359 case Type::Decltype:
360 case Type::UnresolvedUsing:
361 return true;
362
363 case Type::ConstantArray:
364 case Type::IncompleteArray:
365 case Type::VariableArray:
366 case Type::DependentSizedArray:
367 return IsPossiblyOpaquelyQualifiedType(
368 cast<ArrayType>(T)->getElementType());
369
370 default:
371 return false;
372 }
373}
374
Douglas Gregor500d3312009-06-26 18:27:22 +0000375/// \brief Deduce the template arguments by comparing the parameter type and
376/// the argument type (C++ [temp.deduct.type]).
377///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000378/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000379///
380/// \param TemplateParams the template parameters that we are deducing
381///
382/// \param ParamIn the parameter type
383///
384/// \param ArgIn the argument type
385///
386/// \param Info information about the template argument deduction itself
387///
388/// \param Deduced the deduced template arguments
389///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000390/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000391/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000392///
393/// \returns the result of template argument deduction so far. Note that a
394/// "success" result means that template argument deduction has not yet failed,
395/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000396static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000397DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000398 TemplateParameterList *TemplateParams,
399 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000400 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000401 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000402 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000403 // We only want to look at the canonical types, since typedefs and
404 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000405 QualType Param = S.Context.getCanonicalType(ParamIn);
406 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000407
Douglas Gregor500d3312009-06-26 18:27:22 +0000408 // C++0x [temp.deduct.call]p4 bullet 1:
409 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000410 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000411 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000412 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000413 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000414 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000415 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
416 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000417 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000420 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000421 if (!Param->isDependentType()) {
422 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
423
424 return Sema::TDK_NonDeducedMismatch;
425 }
426
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000427 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000428 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000429
Douglas Gregor199d9912009-06-05 00:53:49 +0000430 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000431 // A template type argument T, a template template argument TT or a
432 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000433 // the following forms:
434 //
435 // T
436 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000437 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000438 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000439 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000440 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000442 // If the argument type is an array type, move the qualifiers up to the
443 // top level, so they can be matched with the qualifiers on the parameter.
444 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000445 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000446 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000447 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000448 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000449 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000450 RecanonicalizeArg = true;
451 }
452 }
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000454 // The argument type can not be less qualified than the parameter
455 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000456 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000457 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000458 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000459 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000460 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000461 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000462
463 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000464 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000465 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000466
467 // local manipulation is okay because it's canonical
468 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000469 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000470 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000472 if (Deduced[Index].isNull())
John McCall833ca992009-10-29 08:12:44 +0000473 Deduced[Index] = TemplateArgument(DeducedType);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000474 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000475 // C++ [temp.deduct.type]p2:
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000476 // [...] If type deduction cannot be done for any P/A pair, or if for
Mike Stump1eb44332009-09-09 15:08:12 +0000477 // any pair the deduction leads to more than one possible set of
478 // deduced values, or if different pairs yield different deduced
479 // values, or if any template argument remains neither deduced nor
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000480 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000481 if (Deduced[Index].getAsType() != DeducedType) {
Mike Stump1eb44332009-09-09 15:08:12 +0000482 Info.Param
Douglas Gregorf67875d2009-06-12 18:26:56 +0000483 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
484 Info.FirstArg = Deduced[Index];
John McCall833ca992009-10-29 08:12:44 +0000485 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000486 return Sema::TDK_Inconsistent;
487 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000488 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000489 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000490 }
491
Douglas Gregorf67875d2009-06-12 18:26:56 +0000492 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000493 Info.FirstArg = TemplateArgument(ParamIn);
494 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000495
Douglas Gregor508f1c82009-06-26 23:10:12 +0000496 // Check the cv-qualifiers on the parameter and argument types.
497 if (!(TDF & TDF_IgnoreQualifiers)) {
498 if (TDF & TDF_ParamWithReferenceType) {
499 if (Param.isMoreQualifiedThan(Arg))
500 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000501 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000502 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000503 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000504 }
505 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000506
Douglas Gregord560d502009-06-04 00:21:18 +0000507 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000508 // No deduction possible for these types
509 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000510 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor199d9912009-06-05 00:53:49 +0000512 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000513 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000514 QualType PointeeType;
515 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
516 PointeeType = PointerArg->getPointeeType();
517 } else if (const ObjCObjectPointerType *PointerArg
518 = Arg->getAs<ObjCObjectPointerType>()) {
519 PointeeType = PointerArg->getPointeeType();
520 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000521 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000522 }
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Douglas Gregor41128772009-06-26 23:27:24 +0000524 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000525 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000526 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000527 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000528 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor199d9912009-06-05 00:53:49 +0000531 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000532 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000533 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000534 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000535 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000537 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000538 cast<LValueReferenceType>(Param)->getPointeeType(),
539 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000540 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000541 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000542
Douglas Gregor199d9912009-06-05 00:53:49 +0000543 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000544 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000546 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000547 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000549 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000550 cast<RValueReferenceType>(Param)->getPointeeType(),
551 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000552 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Douglas Gregor199d9912009-06-05 00:53:49 +0000555 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000556 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000558 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000559 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000560 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000561
John McCalle4f26e52010-08-19 00:20:19 +0000562 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000563 return DeduceTemplateArguments(S, TemplateParams,
564 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000565 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000566 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000567 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000568
569 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000570 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000571 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000572 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000573 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000574 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
576 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000577 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000578 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000579 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000580
John McCalle4f26e52010-08-19 00:20:19 +0000581 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000582 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000583 ConstantArrayParm->getElementType(),
584 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000585 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000586 }
587
Douglas Gregor199d9912009-06-05 00:53:49 +0000588 // type [i]
589 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000590 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000591 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000592 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000593
John McCalle4f26e52010-08-19 00:20:19 +0000594 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
595
Douglas Gregor199d9912009-06-05 00:53:49 +0000596 // Check the element type of the arrays
597 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000598 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000599 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000600 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000601 DependentArrayParm->getElementType(),
602 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000603 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000604 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Douglas Gregor199d9912009-06-05 00:53:49 +0000606 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000607 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000608 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
609 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000610 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
612 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000613 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000614 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000615 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000616 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000617 = dyn_cast<ConstantArrayType>(ArrayArg)) {
618 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000619 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
620 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000621 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000622 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000623 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000624 if (const DependentSizedArrayType *DependentArrayArg
625 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000626 return DeduceNonTypeTemplateArgument(S, NTTP,
Douglas Gregor199d9912009-06-05 00:53:49 +0000627 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000628 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor199d9912009-06-05 00:53:49 +0000630 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000631 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000632 }
Mike Stump1eb44332009-09-09 15:08:12 +0000633
634 // type(*)(T)
635 // T(*)()
636 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000637 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000638 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000639 dyn_cast<FunctionProtoType>(Arg);
640 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000641 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
643 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000644 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000645
Mike Stump1eb44332009-09-09 15:08:12 +0000646 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000647 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000648 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000650 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000651 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000653 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000654 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000655
Anders Carlssona27fad52009-06-08 15:19:08 +0000656 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000657 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000658 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000659 FunctionProtoParam->getResultType(),
660 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000661 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000662 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Anders Carlssona27fad52009-06-08 15:19:08 +0000664 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
665 // Check argument types.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000666 // FIXME: Variadic templates.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000667 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000668 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000669 FunctionProtoParam->getArgType(I),
670 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000671 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000672 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Douglas Gregorf67875d2009-06-12 18:26:56 +0000675 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
John McCall3cb0ebd2010-03-10 03:28:59 +0000678 case Type::InjectedClassName: {
679 // Treat a template's injected-class-name as if the template
680 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000681 Param = cast<InjectedClassNameType>(Param)
682 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000683 assert(isa<TemplateSpecializationType>(Param) &&
684 "injected class name is not a template specialization type");
685 // fall through
686 }
687
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000688 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000689 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000690 // TT<T>
691 // TT<i>
692 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000693 case Type::TemplateSpecialization: {
694 const TemplateSpecializationType *SpecParam
695 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000697 // Try to deduce template arguments from the template-id.
698 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000699 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000700 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000702 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000703 // C++ [temp.deduct.call]p3b3:
704 // If P is a class, and P has the form template-id, then A can be a
705 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000706 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000707 // class pointed to by the deduced A.
708 //
709 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000710 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000711 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000712 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
713 // We cannot inspect base classes as part of deduction when the type
714 // is incomplete, so either instantiate any templates necessary to
715 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000716 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000717 return Result;
718
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000719 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000721 // ToVisit is our stack of records that we still need to visit.
722 llvm::SmallPtrSet<const RecordType *, 8> Visited;
723 llvm::SmallVector<const RecordType *, 8> ToVisit;
724 ToVisit.push_back(RecordT);
725 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000726 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
727 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000728 while (!ToVisit.empty()) {
729 // Retrieve the next class in the inheritance hierarchy.
730 const RecordType *NextT = ToVisit.back();
731 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000733 // If we have already seen this type, skip it.
734 if (!Visited.insert(NextT))
735 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000737 // If this is a base class, try to perform template argument
738 // deduction from it.
739 if (NextT != RecordT) {
740 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000741 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000742 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000744 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000745 // note that we had some success. Otherwise, ignore any deductions
746 // from this base class.
747 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000748 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000749 DeducedOrig = Deduced;
750 }
751 else
752 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000755 // Visit base classes
756 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
757 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
758 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000759 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000760 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000761 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000762 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000763 }
764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000766 if (Successful)
767 return Sema::TDK_Success;
768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000772 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000773 }
774
Douglas Gregor637a4092009-06-10 23:47:09 +0000775 // T type::*
776 // T T::*
777 // T (type::*)()
778 // type (T::*)()
779 // type (type::*)(T)
780 // type (T::*)(T)
781 // T (type::*)(T)
782 // T (T::*)()
783 // T (T::*)(T)
784 case Type::MemberPointer: {
785 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
786 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
787 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000788 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000789
Douglas Gregorf67875d2009-06-12 18:26:56 +0000790 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000791 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000792 MemPtrParam->getPointeeType(),
793 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000794 Info, Deduced,
795 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000796 return Result;
797
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000798 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000799 QualType(MemPtrParam->getClass(), 0),
800 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000801 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000802 }
803
Anders Carlsson9a917e42009-06-12 22:56:54 +0000804 // (clang extension)
805 //
Mike Stump1eb44332009-09-09 15:08:12 +0000806 // type(^)(T)
807 // T(^)()
808 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000809 case Type::BlockPointer: {
810 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
811 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Anders Carlsson859ba502009-06-12 16:23:10 +0000813 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000814 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000816 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000817 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000818 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000819 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000820 }
821
Douglas Gregor637a4092009-06-10 23:47:09 +0000822 case Type::TypeOfExpr:
823 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000824 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000825 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000826 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000827
Douglas Gregord560d502009-06-04 00:21:18 +0000828 default:
829 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000830 }
831
832 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000833 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000834}
835
Douglas Gregorf67875d2009-06-12 18:26:56 +0000836static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000837DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000838 TemplateParameterList *TemplateParams,
839 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000840 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000841 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000842 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000843 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000844 case TemplateArgument::Null:
845 assert(false && "Null template argument in parameter list");
846 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
848 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000849 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000850 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000851 Arg.getAsType(), Info, Deduced, 0);
852 Info.FirstArg = Param;
853 Info.SecondArg = Arg;
854 return Sema::TDK_NonDeducedMismatch;
855
856 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000857 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000858 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000859 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000860 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000861 Info.FirstArg = Param;
862 Info.SecondArg = Arg;
863 return Sema::TDK_NonDeducedMismatch;
864
Douglas Gregor199d9912009-06-05 00:53:49 +0000865 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000866 if (Arg.getKind() == TemplateArgument::Declaration &&
867 Param.getAsDecl()->getCanonicalDecl() ==
868 Arg.getAsDecl()->getCanonicalDecl())
869 return Sema::TDK_Success;
870
Douglas Gregorf67875d2009-06-12 18:26:56 +0000871 Info.FirstArg = Param;
872 Info.SecondArg = Arg;
873 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Douglas Gregor199d9912009-06-05 00:53:49 +0000875 case TemplateArgument::Integral:
876 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000877 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000878 return Sema::TDK_Success;
879
880 Info.FirstArg = Param;
881 Info.SecondArg = Arg;
882 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000883 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000884
885 if (Arg.getKind() == TemplateArgument::Expression) {
886 Info.FirstArg = Param;
887 Info.SecondArg = Arg;
888 return Sema::TDK_NonDeducedMismatch;
889 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000890
Douglas Gregorf67875d2009-06-12 18:26:56 +0000891 Info.FirstArg = Param;
892 Info.SecondArg = Arg;
893 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000896 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000897 = getDeducedParameterFromExpr(Param.getAsExpr())) {
898 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000899 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000901 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000902 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000903 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000904 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000905 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000906 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +0000907 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000908 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +0000909 Info, Deduced);
910
Douglas Gregorf67875d2009-06-12 18:26:56 +0000911 Info.FirstArg = Param;
912 Info.SecondArg = Arg;
913 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor199d9912009-06-05 00:53:49 +0000916 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000917 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000918 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000919 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +0000920 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +0000921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregorf67875d2009-06-12 18:26:56 +0000923 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000924}
925
Douglas Gregor20a55e22010-12-22 18:17:10 +0000926/// \brief Determine whether there is a template argument to be used for
927/// deduction.
928///
929/// This routine "expands" argument packs in-place, overriding its input
930/// parameters so that \c Args[ArgIdx] will be the available template argument.
931///
932/// \returns true if there is another template argument (which will be at
933/// \c Args[ArgIdx]), false otherwise.
934static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
935 unsigned &ArgIdx,
936 unsigned &NumArgs) {
937 if (ArgIdx == NumArgs)
938 return false;
939
940 const TemplateArgument &Arg = Args[ArgIdx];
941 if (Arg.getKind() != TemplateArgument::Pack)
942 return true;
943
944 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
945 Args = Arg.pack_begin();
946 NumArgs = Arg.pack_size();
947 ArgIdx = 0;
948 return ArgIdx < NumArgs;
949}
950
Douglas Gregore02e2622010-12-22 21:19:48 +0000951/// \brief Retrieve the depth and index of an unexpanded parameter pack.
952static std::pair<unsigned, unsigned>
953getDepthAndIndex(UnexpandedParameterPack UPP) {
954 if (const TemplateTypeParmType *TTP
955 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
956 return std::make_pair(TTP->getDepth(), TTP->getIndex());
957
958 if (TemplateTypeParmDecl *TTP = UPP.first.dyn_cast<TemplateTypeParmDecl *>())
959 return std::make_pair(TTP->getDepth(), TTP->getIndex());
960
961 if (NonTypeTemplateParmDecl *NTTP
962 = UPP.first.dyn_cast<NonTypeTemplateParmDecl *>())
963 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
964
965 TemplateTemplateParmDecl *TTP = UPP.first.get<TemplateTemplateParmDecl *>();
966 return std::make_pair(TTP->getDepth(), TTP->getIndex());
967}
968
Douglas Gregor20a55e22010-12-22 18:17:10 +0000969static Sema::TemplateDeductionResult
970DeduceTemplateArguments(Sema &S,
971 TemplateParameterList *TemplateParams,
972 const TemplateArgument *Params, unsigned NumParams,
973 const TemplateArgument *Args, unsigned NumArgs,
974 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000975 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
976 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +0000977 // C++0x [temp.deduct.type]p9:
978 // If the template argument list of P contains a pack expansion that is not
979 // the last template argument, the entire template argument list is a
980 // non-deduced context.
981 // FIXME: Implement this.
982
983
984 // C++0x [temp.deduct.type]p9:
985 // If P has a form that contains <T> or <i>, then each argument Pi of the
986 // respective template argument list P is compared with the corresponding
987 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000988 unsigned ArgIdx = 0, ParamIdx = 0;
989 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
990 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +0000991 // FIXME: Variadic templates.
992 // What do we do if the argument is a pack expansion?
993
Douglas Gregor20a55e22010-12-22 18:17:10 +0000994 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +0000995 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000996
997 // Check whether we have enough arguments.
998 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +0000999 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1000 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001001
Douglas Gregore02e2622010-12-22 21:19:48 +00001002 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001003 if (Sema::TemplateDeductionResult Result
1004 = DeduceTemplateArguments(S, TemplateParams,
1005 Params[ParamIdx], Args[ArgIdx],
1006 Info, Deduced))
1007 return Result;
1008
1009 // Move to the next argument.
1010 ++ArgIdx;
1011 continue;
1012 }
1013
Douglas Gregore02e2622010-12-22 21:19:48 +00001014 // The parameter is a pack expansion.
1015
1016 // C++0x [temp.deduct.type]p9:
1017 // If Pi is a pack expansion, then the pattern of Pi is compared with
1018 // each remaining argument in the template argument list of A. Each
1019 // comparison deduces template arguments for subsequent positions in the
1020 // template parameter packs expanded by Pi.
1021 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1022
1023 // Compute the set of template parameter indices that correspond to
1024 // parameter packs expanded by the pack expansion.
1025 llvm::SmallVector<unsigned, 2> PackIndices;
1026 {
1027 llvm::BitVector SawIndices(TemplateParams->size());
1028 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1029 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1030 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1031 unsigned Depth, Index;
1032 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1033 if (Depth == 0 && !SawIndices[Index]) {
1034 SawIndices[Index] = true;
1035 PackIndices.push_back(Index);
1036 }
1037 }
1038 }
1039 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1040
1041 // FIXME: If there are no remaining arguments, we can bail out early
1042 // and set any deduced parameter packs to an empty argument pack.
1043 // The latter part of this is a (minor) correctness issue.
1044
1045 // Save the deduced template arguments for each parameter pack expanded
1046 // by this pack expansion, then clear out the deduction.
1047 llvm::SmallVector<DeducedTemplateArgument, 2>
1048 SavedPacks(PackIndices.size());
1049 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1050 SavedPacks[I] = Deduced[PackIndices[I]];
1051 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1052 }
1053
1054 // Keep track of the deduced template arguments for each parameter pack
1055 // expanded by this pack expansion (the outer index) and for each
1056 // template argument (the inner SmallVectors).
1057 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1058 NewlyDeducedPacks(PackIndices.size());
1059 bool HasAnyArguments = false;
1060 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1061 HasAnyArguments = true;
1062
1063 // Deduce template arguments from the pattern.
1064 if (Sema::TemplateDeductionResult Result
1065 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1066 Info, Deduced))
1067 return Result;
1068
1069 // Capture the deduced template arguments for each parameter pack expanded
1070 // by this pack expansion, add them to the list of arguments we've deduced
1071 // for that pack, then clear out the deduced argument.
1072 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1073 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1074 if (!DeducedArg.isNull()) {
1075 NewlyDeducedPacks[I].push_back(DeducedArg);
1076 DeducedArg = DeducedTemplateArgument();
1077 }
1078 }
1079
1080 ++ArgIdx;
1081 }
1082
1083 // Build argument packs for each of the parameter packs expanded by this
1084 // pack expansion.
1085 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1086 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1087 // We were not able to deduce anything for this parameter pack,
1088 // so just restore the saved argument pack.
1089 Deduced[PackIndices[I]] = SavedPacks[I];
1090 continue;
1091 }
1092
1093 if (!SavedPacks[I].isNull()) {
1094 // FIXME: Check against the existing argument pack.
1095 S.Diag(Info.getLocation(), diag::err_pack_expansion_deduction_compare);
1096 return Sema::TDK_TooFewArguments;
1097 }
1098
1099 if (NewlyDeducedPacks[I].empty()) {
1100 // If we deduced an empty argument pack, create it now.
1101 Deduced[PackIndices[I]]
1102 = DeducedTemplateArgument(TemplateArgument(0, 0));
1103 continue;
1104 }
1105
1106 TemplateArgument *ArgumentPack
1107 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1108 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1109 ArgumentPack);
1110 Deduced[PackIndices[I]]
1111 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
1112 NewlyDeducedPacks[I].size()),
1113 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1114 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001115 }
1116
1117 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001118 if (NumberOfArgumentsMustMatch &&
1119 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001120 return Sema::TDK_TooManyArguments;
1121
1122 return Sema::TDK_Success;
1123}
1124
Mike Stump1eb44332009-09-09 15:08:12 +00001125static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001126DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001127 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001128 const TemplateArgumentList &ParamList,
1129 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001130 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001131 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001132 return DeduceTemplateArguments(S, TemplateParams,
1133 ParamList.data(), ParamList.size(),
1134 ArgList.data(), ArgList.size(),
1135 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001136}
1137
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001138/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001139static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001140 const TemplateArgument &X,
1141 const TemplateArgument &Y) {
1142 if (X.getKind() != Y.getKind())
1143 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001145 switch (X.getKind()) {
1146 case TemplateArgument::Null:
1147 assert(false && "Comparing NULL template argument");
1148 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001150 case TemplateArgument::Type:
1151 return Context.getCanonicalType(X.getAsType()) ==
1152 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001154 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001155 return X.getAsDecl()->getCanonicalDecl() ==
1156 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Douglas Gregor788cd062009-11-11 01:00:40 +00001158 case TemplateArgument::Template:
1159 return Context.getCanonicalTemplateName(X.getAsTemplate())
1160 .getAsVoidPointer() ==
1161 Context.getCanonicalTemplateName(Y.getAsTemplate())
1162 .getAsVoidPointer();
1163
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001164 case TemplateArgument::Integral:
1165 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Douglas Gregor788cd062009-11-11 01:00:40 +00001167 case TemplateArgument::Expression: {
1168 llvm::FoldingSetNodeID XID, YID;
1169 X.getAsExpr()->Profile(XID, Context, true);
1170 Y.getAsExpr()->Profile(YID, Context, true);
1171 return XID == YID;
1172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001174 case TemplateArgument::Pack:
1175 if (X.pack_size() != Y.pack_size())
1176 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001177
1178 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1179 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001180 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001181 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001182 if (!isSameTemplateArg(Context, *XP, *YP))
1183 return false;
1184
1185 return true;
1186 }
1187
1188 return false;
1189}
1190
1191/// \brief Helper function to build a TemplateParameter when we don't
1192/// know its type statically.
1193static TemplateParameter makeTemplateParameter(Decl *D) {
1194 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1195 return TemplateParameter(TTP);
1196 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1197 return TemplateParameter(NTTP);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001199 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1200}
1201
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001202/// Complete template argument deduction for a class template partial
1203/// specialization.
1204static Sema::TemplateDeductionResult
1205FinishTemplateArgumentDeduction(Sema &S,
1206 ClassTemplatePartialSpecializationDecl *Partial,
1207 const TemplateArgumentList &TemplateArgs,
1208 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001209 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001210 // Trap errors.
1211 Sema::SFINAETrap Trap(S);
1212
1213 Sema::ContextRAII SavedContext(S, Partial);
1214
1215 // C++ [temp.deduct.type]p2:
1216 // [...] or if any template argument remains neither deduced nor
1217 // explicitly specified, template argument deduction fails.
Douglas Gregore02e2622010-12-22 21:19:48 +00001218 // FIXME: Variadic templates Empty parameter packs?
Douglas Gregor910f8002010-11-07 23:05:16 +00001219 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001220 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1221 if (Deduced[I].isNull()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001222 unsigned ParamIdx = I;
1223 if (ParamIdx >= Partial->getTemplateParameters()->size())
1224 ParamIdx = Partial->getTemplateParameters()->size() - 1;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001225 Decl *Param
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001226 = const_cast<NamedDecl *>(
Douglas Gregore02e2622010-12-22 21:19:48 +00001227 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001228 Info.Param = makeTemplateParameter(Param);
1229 return Sema::TDK_Incomplete;
1230 }
1231
Douglas Gregor910f8002010-11-07 23:05:16 +00001232 Builder.push_back(Deduced[I]);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001233 }
1234
1235 // Form the template argument list from the deduced template arguments.
1236 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001237 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1238 Builder.size());
1239
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001240 Info.reset(DeducedArgumentList);
1241
1242 // Substitute the deduced template arguments into the template
1243 // arguments of the class template partial specialization, and
1244 // verify that the instantiated template arguments are both valid
1245 // and are equivalent to the template arguments originally provided
1246 // to the class template.
1247 // FIXME: Do we have to correct the types of deduced non-type template
1248 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001249 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001250 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1251 const TemplateArgumentLoc *PartialTemplateArgs
1252 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001253
1254 // Note that we don't provide the langle and rangle locations.
1255 TemplateArgumentListInfo InstArgs;
1256
Douglas Gregore02e2622010-12-22 21:19:48 +00001257 if (S.Subst(PartialTemplateArgs,
1258 Partial->getNumTemplateArgsAsWritten(),
1259 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1260 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1261 if (ParamIdx >= Partial->getTemplateParameters()->size())
1262 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1263
1264 Decl *Param
1265 = const_cast<NamedDecl *>(
1266 Partial->getTemplateParameters()->getParam(ParamIdx));
1267 Info.Param = makeTemplateParameter(Param);
1268 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1269 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001270 }
1271
Douglas Gregor910f8002010-11-07 23:05:16 +00001272 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001273 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorec20f462010-05-08 20:07:26 +00001274 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001275 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001276
Douglas Gregor910f8002010-11-07 23:05:16 +00001277 for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1278 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001279
1280 Decl *Param = const_cast<NamedDecl *>(
1281 ClassTemplate->getTemplateParameters()->getParam(I));
1282
1283 if (InstArg.getKind() == TemplateArgument::Expression) {
1284 // When the argument is an expression, check the expression result
1285 // against the actual template parameter to get down to the canonical
1286 // template argument.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001287 // FIXME: Variadic templates.
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001288 Expr *InstExpr = InstArg.getAsExpr();
1289 if (NonTypeTemplateParmDecl *NTTP
1290 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1291 if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1292 Info.Param = makeTemplateParameter(Param);
1293 Info.FirstArg = Partial->getTemplateArgs()[I];
1294 return Sema::TDK_SubstitutionFailure;
1295 }
1296 }
1297 }
1298
1299 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1300 Info.Param = makeTemplateParameter(Param);
1301 Info.FirstArg = TemplateArgs[I];
1302 Info.SecondArg = InstArg;
1303 return Sema::TDK_NonDeducedMismatch;
1304 }
1305 }
1306
1307 if (Trap.hasErrorOccurred())
1308 return Sema::TDK_SubstitutionFailure;
1309
1310 return Sema::TDK_Success;
1311}
1312
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001313/// \brief Perform template argument deduction to determine whether
1314/// the given template arguments match the given class template
1315/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001316Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001317Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001318 const TemplateArgumentList &TemplateArgs,
1319 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001320 // C++ [temp.class.spec.match]p2:
1321 // A partial specialization matches a given actual template
1322 // argument list if the template arguments of the partial
1323 // specialization can be deduced from the actual template argument
1324 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001325 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001326 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001327 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001328 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001329 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001330 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001331 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001332 TemplateArgs, Info, Deduced))
1333 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001334
Douglas Gregor637a4092009-06-10 23:47:09 +00001335 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001336 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001337 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001338 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001339
Douglas Gregorbb260412009-06-14 08:02:22 +00001340 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001341 return Sema::TDK_SubstitutionFailure;
1342
1343 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1344 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001345}
Douglas Gregor031a5882009-06-13 00:26:55 +00001346
Douglas Gregor41128772009-06-26 23:27:24 +00001347/// \brief Determine whether the given type T is a simple-template-id type.
1348static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001349 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001350 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001351 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Douglas Gregor41128772009-06-26 23:27:24 +00001353 return false;
1354}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001355
1356/// \brief Substitute the explicitly-provided template arguments into the
1357/// given function template according to C++ [temp.arg.explicit].
1358///
1359/// \param FunctionTemplate the function template into which the explicit
1360/// template arguments will be substituted.
1361///
Mike Stump1eb44332009-09-09 15:08:12 +00001362/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001363/// arguments.
1364///
Mike Stump1eb44332009-09-09 15:08:12 +00001365/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001366/// with the converted and checked explicit template arguments.
1367///
Mike Stump1eb44332009-09-09 15:08:12 +00001368/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001369/// parameters.
1370///
1371/// \param FunctionType if non-NULL, the result type of the function template
1372/// will also be instantiated and the pointed-to value will be updated with
1373/// the instantiated function type.
1374///
1375/// \param Info if substitution fails for any reason, this object will be
1376/// populated with more information about the failure.
1377///
1378/// \returns TDK_Success if substitution was successful, or some failure
1379/// condition.
1380Sema::TemplateDeductionResult
1381Sema::SubstituteExplicitTemplateArguments(
1382 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001383 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001384 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001385 llvm::SmallVectorImpl<QualType> &ParamTypes,
1386 QualType *FunctionType,
1387 TemplateDeductionInfo &Info) {
1388 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1389 TemplateParameterList *TemplateParams
1390 = FunctionTemplate->getTemplateParameters();
1391
John McCalld5532b62009-11-23 01:53:49 +00001392 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001393 // No arguments to substitute; just copy over the parameter types and
1394 // fill in the function type.
1395 for (FunctionDecl::param_iterator P = Function->param_begin(),
1396 PEnd = Function->param_end();
1397 P != PEnd;
1398 ++P)
1399 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor83314aa2009-07-08 20:55:45 +00001401 if (FunctionType)
1402 *FunctionType = Function->getType();
1403 return TDK_Success;
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregor83314aa2009-07-08 20:55:45 +00001406 // Substitution of the explicit template arguments into a function template
1407 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001408 SFINAETrap Trap(*this);
1409
Douglas Gregor83314aa2009-07-08 20:55:45 +00001410 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001411 // Template arguments that are present shall be specified in the
1412 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001413 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001414 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001415 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
1417 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001418 // explicitly-specified template arguments against this function template,
1419 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001420 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001421 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001422 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1423 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001424 if (Inst)
1425 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Douglas Gregor83314aa2009-07-08 20:55:45 +00001427 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001428 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001429 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001430 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001431 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001432 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001433 if (Index >= TemplateParams->size())
1434 Index = TemplateParams->size() - 1;
1435 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001436 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001437 }
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Douglas Gregor83314aa2009-07-08 20:55:45 +00001439 // Form the template argument list from the explicitly-specified
1440 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001441 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001442 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001443 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
John McCalldf41f182010-10-12 19:40:14 +00001445 // Template argument deduction and the final substitution should be
1446 // done in the context of the templated declaration. Explicit
1447 // argument substitution, on the other hand, needs to happen in the
1448 // calling context.
1449 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1450
Douglas Gregor83314aa2009-07-08 20:55:45 +00001451 // Instantiate the types of each of the function parameters given the
1452 // explicitly-specified template arguments.
1453 for (FunctionDecl::param_iterator P = Function->param_begin(),
1454 PEnd = Function->param_end();
1455 P != PEnd;
1456 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001457 QualType ParamType
1458 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001459 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1460 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001461 if (ParamType.isNull() || Trap.hasErrorOccurred())
1462 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregor83314aa2009-07-08 20:55:45 +00001464 ParamTypes.push_back(ParamType);
1465 }
1466
1467 // If the caller wants a full function type back, instantiate the return
1468 // type and form that function type.
1469 if (FunctionType) {
1470 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001471 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001472 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001473 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001474
1475 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001476 = SubstType(Proto->getResultType(),
1477 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1478 Function->getTypeSpecStartLoc(),
1479 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001480 if (ResultType.isNull() || Trap.hasErrorOccurred())
1481 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001482
1483 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001484 ParamTypes.data(), ParamTypes.size(),
1485 Proto->isVariadic(),
1486 Proto->getTypeQuals(),
1487 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001488 Function->getDeclName(),
1489 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001490 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1491 return TDK_SubstitutionFailure;
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregor83314aa2009-07-08 20:55:45 +00001494 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001495 // Trailing template arguments that can be deduced (14.8.2) may be
1496 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001497 // template arguments can be deduced, they may all be omitted; in this
1498 // case, the empty template argument list <> itself may also be omitted.
1499 //
1500 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001501 // set of deduced template arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001502 //
1503 // FIXME: Variadic templates?
Douglas Gregor83314aa2009-07-08 20:55:45 +00001504 Deduced.reserve(TemplateParams->size());
1505 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001506 Deduced.push_back(ExplicitArgumentList->get(I));
1507
Douglas Gregor83314aa2009-07-08 20:55:45 +00001508 return TDK_Success;
1509}
1510
Douglas Gregor02024a92010-03-28 02:42:43 +00001511/// \brief Allocate a TemplateArgumentLoc where all locations have
1512/// been initialized to the given location.
1513///
1514/// \param S The semantic analysis object.
1515///
1516/// \param The template argument we are producing template argument
1517/// location information for.
1518///
1519/// \param NTTPType For a declaration template argument, the type of
1520/// the non-type template parameter that corresponds to this template
1521/// argument.
1522///
1523/// \param Loc The source location to use for the resulting template
1524/// argument.
1525static TemplateArgumentLoc
1526getTrivialTemplateArgumentLoc(Sema &S,
1527 const TemplateArgument &Arg,
1528 QualType NTTPType,
1529 SourceLocation Loc) {
1530 switch (Arg.getKind()) {
1531 case TemplateArgument::Null:
1532 llvm_unreachable("Can't get a NULL template argument here");
1533 break;
1534
1535 case TemplateArgument::Type:
1536 return TemplateArgumentLoc(Arg,
1537 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1538
1539 case TemplateArgument::Declaration: {
1540 Expr *E
1541 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1542 .takeAs<Expr>();
1543 return TemplateArgumentLoc(TemplateArgument(E), E);
1544 }
1545
1546 case TemplateArgument::Integral: {
1547 Expr *E
1548 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1549 return TemplateArgumentLoc(TemplateArgument(E), E);
1550 }
1551
1552 case TemplateArgument::Template:
1553 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1554
1555 case TemplateArgument::Expression:
1556 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1557
1558 case TemplateArgument::Pack:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001559 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
Douglas Gregor02024a92010-03-28 02:42:43 +00001560 }
1561
1562 return TemplateArgumentLoc();
1563}
1564
Mike Stump1eb44332009-09-09 15:08:12 +00001565/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001566/// checking the deduced template arguments for completeness and forming
1567/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001568Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001569Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001570 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1571 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001572 FunctionDecl *&Specialization,
1573 TemplateDeductionInfo &Info) {
1574 TemplateParameterList *TemplateParams
1575 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Douglas Gregor83314aa2009-07-08 20:55:45 +00001577 // Template argument deduction for function templates in a SFINAE context.
1578 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001579 SFINAETrap Trap(*this);
1580
Douglas Gregor83314aa2009-07-08 20:55:45 +00001581 // Enter a new template instantiation context while we instantiate the
1582 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001584 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001585 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1586 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001587 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001588 return TDK_InstantiationDepth;
1589
John McCall96db3102010-04-29 01:18:58 +00001590 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001591
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001592 // C++ [temp.deduct.type]p2:
1593 // [...] or if any template argument remains neither deduced nor
1594 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001595 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001596 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001597 // FIXME: Variadic templates. Unwrap argument packs?
Douglas Gregor02024a92010-03-28 02:42:43 +00001598 NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001599 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001600 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001601 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001602 // argument, because it was explicitly-specified. Just record the
1603 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001604 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001605 continue;
1606 }
1607
1608 // We have deduced this argument, so it still needs to be
1609 // checked and converted.
1610
1611 // First, for a non-type template parameter type that is
1612 // initialized by a declaration, we need the type of the
1613 // corresponding non-type template parameter.
1614 QualType NTTPType;
1615 if (NonTypeTemplateParmDecl *NTTP
1616 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1617 if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1618 NTTPType = NTTP->getType();
1619 if (NTTPType->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001620 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1621 Builder.data(), Builder.size());
Douglas Gregor02024a92010-03-28 02:42:43 +00001622 NTTPType = SubstType(NTTPType,
1623 MultiLevelTemplateArgumentList(TemplateArgs),
1624 NTTP->getLocation(),
1625 NTTP->getDeclName());
1626 if (NTTPType.isNull()) {
1627 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001628 // FIXME: These template arguments are temporary. Free them!
1629 Info.reset(TemplateArgumentList::CreateCopy(Context,
1630 Builder.data(),
1631 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001632 return TDK_SubstitutionFailure;
1633 }
1634 }
1635 }
1636 }
1637
1638 // Convert the deduced template argument into a template
1639 // argument that we can check, almost as if the user had written
1640 // the template argument explicitly.
1641 TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1642 Deduced[I],
1643 NTTPType,
Douglas Gregor9b623632010-10-12 23:32:35 +00001644 Info.getLocation());
Douglas Gregor02024a92010-03-28 02:42:43 +00001645
1646 // Check the template argument, converting it as necessary.
1647 if (CheckTemplateArgument(Param, Arg,
1648 FunctionTemplate,
1649 FunctionTemplate->getLocation(),
1650 FunctionTemplate->getSourceRange().getEnd(),
1651 Builder,
1652 Deduced[I].wasDeducedFromArrayBound()
1653 ? CTAK_DeducedFromArrayBound
1654 : CTAK_Deduced)) {
1655 Info.Param = makeTemplateParameter(
1656 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001657 // FIXME: These template arguments are temporary. Free them!
1658 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1659 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001660 return TDK_SubstitutionFailure;
1661 }
1662
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001663 continue;
1664 }
1665
1666 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001667 TemplateArgumentLoc DefArg
1668 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1669 FunctionTemplate->getLocation(),
1670 FunctionTemplate->getSourceRange().getEnd(),
1671 Param,
1672 Builder);
1673
1674 // If there was no default argument, deduction is incomplete.
1675 if (DefArg.getArgument().isNull()) {
1676 Info.Param = makeTemplateParameter(
1677 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1678 return TDK_Incomplete;
1679 }
1680
1681 // Check whether we can actually use the default argument.
1682 if (CheckTemplateArgument(Param, DefArg,
1683 FunctionTemplate,
1684 FunctionTemplate->getLocation(),
1685 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001686 Builder,
1687 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001688 Info.Param = makeTemplateParameter(
1689 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001690 // FIXME: These template arguments are temporary. Free them!
1691 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1692 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001693 return TDK_SubstitutionFailure;
1694 }
1695
1696 // If we get here, we successfully used the default template argument.
1697 }
1698
1699 // Form the template argument list from the deduced template arguments.
1700 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001701 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001702 Info.reset(DeducedArgumentList);
1703
Mike Stump1eb44332009-09-09 15:08:12 +00001704 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001705 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001706 DeclContext *Owner = FunctionTemplate->getDeclContext();
1707 if (FunctionTemplate->getFriendObjectKind())
1708 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001709 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001710 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001711 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001712 if (!Specialization)
1713 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregorf8825742009-09-15 18:26:13 +00001715 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1716 FunctionTemplate->getCanonicalDecl());
1717
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001719 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001720 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1721 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001722 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregor83314aa2009-07-08 20:55:45 +00001724 // There may have been an error that did not prevent us from constructing a
1725 // declaration. Mark the declaration invalid and return with a substitution
1726 // failure.
1727 if (Trap.hasErrorOccurred()) {
1728 Specialization->setInvalidDecl(true);
1729 return TDK_SubstitutionFailure;
1730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Douglas Gregor9b623632010-10-12 23:32:35 +00001732 // If we suppressed any diagnostics while performing template argument
1733 // deduction, and if we haven't already instantiated this declaration,
1734 // keep track of these diagnostics. They'll be emitted if this specialization
1735 // is actually used.
1736 if (Info.diag_begin() != Info.diag_end()) {
1737 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1738 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1739 if (Pos == SuppressedDiagnostics.end())
1740 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1741 .append(Info.diag_begin(), Info.diag_end());
1742 }
1743
Mike Stump1eb44332009-09-09 15:08:12 +00001744 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001745}
1746
John McCall9c72c602010-08-27 09:08:28 +00001747/// Gets the type of a function for template-argument-deducton
1748/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001749static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001750 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001751 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001752 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001753 if (Method->isInstance()) {
1754 // An instance method that's referenced in a form that doesn't
1755 // look like a member pointer is just invalid.
1756 if (!R.HasFormOfMemberPointer) return QualType();
1757
John McCalleff92132010-02-02 02:21:27 +00001758 return Context.getMemberPointerType(Fn->getType(),
1759 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001760 }
1761
1762 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001763 return Context.getPointerType(Fn->getType());
1764}
1765
1766/// Apply the deduction rules for overload sets.
1767///
1768/// \return the null type if this argument should be treated as an
1769/// undeduced context
1770static QualType
1771ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001772 Expr *Arg, QualType ParamType,
1773 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001774
1775 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001776
John McCall9c72c602010-08-27 09:08:28 +00001777 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001778
Douglas Gregor75f21af2010-08-30 21:04:23 +00001779 // C++0x [temp.deduct.call]p4
1780 unsigned TDF = 0;
1781 if (ParamWasReference)
1782 TDF |= TDF_ParamWithReferenceType;
1783 if (R.IsAddressOfOperand)
1784 TDF |= TDF_IgnoreQualifiers;
1785
John McCalleff92132010-02-02 02:21:27 +00001786 // If there were explicit template arguments, we can only find
1787 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1788 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001789 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001790 // But we can still look for an explicit specialization.
1791 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001792 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001793 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001794 return QualType();
1795 }
1796
1797 // C++0x [temp.deduct.call]p6:
1798 // When P is a function type, pointer to function type, or pointer
1799 // to member function type:
1800
1801 if (!ParamType->isFunctionType() &&
1802 !ParamType->isFunctionPointerType() &&
1803 !ParamType->isMemberFunctionPointerType())
1804 return QualType();
1805
1806 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001807 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1808 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001809 NamedDecl *D = (*I)->getUnderlyingDecl();
1810
1811 // - If the argument is an overload set containing one or more
1812 // function templates, the parameter is treated as a
1813 // non-deduced context.
1814 if (isa<FunctionTemplateDecl>(D))
1815 return QualType();
1816
1817 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001818 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1819 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001820
Douglas Gregor75f21af2010-08-30 21:04:23 +00001821 // Function-to-pointer conversion.
1822 if (!ParamWasReference && ParamType->isPointerType() &&
1823 ArgType->isFunctionType())
1824 ArgType = S.Context.getPointerType(ArgType);
1825
John McCalleff92132010-02-02 02:21:27 +00001826 // - If the argument is an overload set (not containing function
1827 // templates), trial argument deduction is attempted using each
1828 // of the members of the set. If deduction succeeds for only one
1829 // of the overload set members, that member is used as the
1830 // argument value for the deduction. If deduction succeeds for
1831 // more than one member of the overload set the parameter is
1832 // treated as a non-deduced context.
1833
1834 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1835 // Type deduction is done independently for each P/A pair, and
1836 // the deduced template argument values are then combined.
1837 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00001838 llvm::SmallVector<DeducedTemplateArgument, 8>
1839 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00001840 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00001841 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001842 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00001843 ParamType, ArgType,
1844 Info, Deduced, TDF);
1845 if (Result) continue;
1846 if (!Match.isNull()) return QualType();
1847 Match = ArgType;
1848 }
1849
1850 return Match;
1851}
1852
Douglas Gregore53060f2009-06-25 22:08:12 +00001853/// \brief Perform template argument deduction from a function call
1854/// (C++ [temp.deduct.call]).
1855///
1856/// \param FunctionTemplate the function template for which we are performing
1857/// template argument deduction.
1858///
Douglas Gregor48026d22010-01-11 18:40:55 +00001859/// \param ExplicitTemplateArguments the explicit template arguments provided
1860/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001861///
Douglas Gregore53060f2009-06-25 22:08:12 +00001862/// \param Args the function call arguments
1863///
1864/// \param NumArgs the number of arguments in Args
1865///
Douglas Gregor48026d22010-01-11 18:40:55 +00001866/// \param Name the name of the function being called. This is only significant
1867/// when the function template is a conversion function template, in which
1868/// case this routine will also perform template argument deduction based on
1869/// the function to which
1870///
Douglas Gregore53060f2009-06-25 22:08:12 +00001871/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001872/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00001873/// template argument deduction.
1874///
1875/// \param Info the argument will be updated to provide additional information
1876/// about template argument deduction.
1877///
1878/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001879Sema::TemplateDeductionResult
1880Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00001881 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001882 Expr **Args, unsigned NumArgs,
1883 FunctionDecl *&Specialization,
1884 TemplateDeductionInfo &Info) {
1885 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001886
Douglas Gregore53060f2009-06-25 22:08:12 +00001887 // C++ [temp.deduct.call]p1:
1888 // Template argument deduction is done by comparing each function template
1889 // parameter type (call it P) with the type of the corresponding argument
1890 // of the call (call it A) as described below.
1891 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001892 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001893 return TDK_TooFewArguments;
1894 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001895 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001896 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00001897 if (!Proto->isVariadic())
1898 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregore53060f2009-06-25 22:08:12 +00001900 CheckArgs = Function->getNumParams();
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001903 // The types of the parameters from which we will perform template argument
1904 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00001905 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00001906 TemplateParameterList *TemplateParams
1907 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001908 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001909 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00001910 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00001911 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001912 TemplateDeductionResult Result =
1913 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001914 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001915 Deduced,
1916 ParamTypes,
1917 0,
1918 Info);
1919 if (Result)
1920 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001921
1922 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001923 } else {
1924 // Just fill in the parameter types from the function declaration.
1925 for (unsigned I = 0; I != CheckArgs; ++I)
1926 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1927 }
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001929 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001930 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001931 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001932 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001933 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor75f21af2010-08-30 21:04:23 +00001935 // C++0x [temp.deduct.call]p3:
1936 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1937 // are ignored for type deduction.
1938 if (ParamType.getCVRQualifiers())
1939 ParamType = ParamType.getLocalUnqualifiedType();
1940 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
1941 if (ParamRefType) {
1942 // [...] If P is a reference type, the type referred to by P is used
1943 // for type deduction.
1944 ParamType = ParamRefType->getPointeeType();
1945 }
1946
John McCalleff92132010-02-02 02:21:27 +00001947 // Overload sets usually make this parameter an undeduced
1948 // context, but there are sometimes special circumstances.
1949 if (ArgType == Context.OverloadTy) {
1950 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001951 Args[I], ParamType,
1952 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00001953 if (ArgType.isNull())
1954 continue;
1955 }
1956
Douglas Gregor75f21af2010-08-30 21:04:23 +00001957 if (ParamRefType) {
1958 // C++0x [temp.deduct.call]p3:
1959 // [...] If P is of the form T&&, where T is a template parameter, and
1960 // the argument is an lvalue, the type A& is used in place of A for
1961 // type deduction.
1962 if (ParamRefType->isRValueReferenceType() &&
1963 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00001964 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00001965 ArgType = Context.getLValueReferenceType(ArgType);
1966 } else {
1967 // C++ [temp.deduct.call]p2:
1968 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00001969 // - If A is an array type, the pointer type produced by the
1970 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00001971 // A for type deduction; otherwise,
1972 if (ArgType->isArrayType())
1973 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00001974 // - If A is a function type, the pointer type produced by the
1975 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00001976 // of A for type deduction; otherwise,
1977 else if (ArgType->isFunctionType())
1978 ArgType = Context.getPointerType(ArgType);
1979 else {
1980 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1981 // type are ignored for type deduction.
1982 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00001983 if (ArgType.getCVRQualifiers())
1984 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00001985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregore53060f2009-06-25 22:08:12 +00001988 // C++0x [temp.deduct.call]p4:
1989 // In general, the deduction process attempts to find template argument
1990 // values that will make the deduced A identical to A (after the type A
1991 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00001992 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor508f1c82009-06-26 23:10:12 +00001994 // - If the original P is a reference type, the deduced A (i.e., the
1995 // type referred to by the reference) can be more cv-qualified than
1996 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00001997 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00001998 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00001999 // - The transformed A can be another pointer or pointer to member
2000 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002001 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002002 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2003 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002004 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002005 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002006 // transformed A can be a derived class of the deduced A. Likewise,
2007 // if P is a pointer to a class of the form simple-template-id, the
2008 // transformed A can be a pointer to a derived class pointed to by
2009 // the deduced A.
2010 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002011 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002012 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002013 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002014 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregore53060f2009-06-25 22:08:12 +00002016 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002017 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002018 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002019 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002020 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002022 // FIXME: we need to check that the deduced A is the same as A,
2023 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002024 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002025
Mike Stump1eb44332009-09-09 15:08:12 +00002026 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002027 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002028 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002029}
2030
Douglas Gregor83314aa2009-07-08 20:55:45 +00002031/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002032/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2033/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002034///
2035/// \param FunctionTemplate the function template for which we are performing
2036/// template argument deduction.
2037///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002038/// \param ExplicitTemplateArguments the explicitly-specified template
2039/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002040///
2041/// \param ArgFunctionType the function type that will be used as the
2042/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002043/// function template's function type. This type may be NULL, if there is no
2044/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002045///
2046/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002047/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002048/// template argument deduction.
2049///
2050/// \param Info the argument will be updated to provide additional information
2051/// about template argument deduction.
2052///
2053/// \returns the result of template argument deduction.
2054Sema::TemplateDeductionResult
2055Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002056 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002057 QualType ArgFunctionType,
2058 FunctionDecl *&Specialization,
2059 TemplateDeductionInfo &Info) {
2060 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2061 TemplateParameterList *TemplateParams
2062 = FunctionTemplate->getTemplateParameters();
2063 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Douglas Gregor83314aa2009-07-08 20:55:45 +00002065 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002066 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002067 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2068 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002069 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002070 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002071 if (TemplateDeductionResult Result
2072 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002073 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002074 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002075 &FunctionType, Info))
2076 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002077
2078 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002079 }
2080
2081 // Template argument deduction for function templates in a SFINAE context.
2082 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002083 SFINAETrap Trap(*this);
2084
John McCalleff92132010-02-02 02:21:27 +00002085 Deduced.resize(TemplateParams->size());
2086
Douglas Gregor4b52e252009-12-21 23:17:24 +00002087 if (!ArgFunctionType.isNull()) {
2088 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002089 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002090 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002091 FunctionType, ArgFunctionType, Info,
2092 Deduced, 0))
2093 return Result;
2094 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002095
2096 if (TemplateDeductionResult Result
2097 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2098 NumExplicitlySpecified,
2099 Specialization, Info))
2100 return Result;
2101
2102 // If the requested function type does not match the actual type of the
2103 // specialization, template argument deduction fails.
2104 if (!ArgFunctionType.isNull() &&
2105 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2106 return TDK_NonDeducedMismatch;
2107
2108 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002109}
2110
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002111/// \brief Deduce template arguments for a templated conversion
2112/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2113/// conversion function template specialization.
2114Sema::TemplateDeductionResult
2115Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2116 QualType ToType,
2117 CXXConversionDecl *&Specialization,
2118 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002119 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002120 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2121 QualType FromType = Conv->getConversionType();
2122
2123 // Canonicalize the types for deduction.
2124 QualType P = Context.getCanonicalType(FromType);
2125 QualType A = Context.getCanonicalType(ToType);
2126
2127 // C++0x [temp.deduct.conv]p3:
2128 // If P is a reference type, the type referred to by P is used for
2129 // type deduction.
2130 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2131 P = PRef->getPointeeType();
2132
2133 // C++0x [temp.deduct.conv]p3:
2134 // If A is a reference type, the type referred to by A is used
2135 // for type deduction.
2136 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2137 A = ARef->getPointeeType();
2138 // C++ [temp.deduct.conv]p2:
2139 //
Mike Stump1eb44332009-09-09 15:08:12 +00002140 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002141 else {
2142 assert(!A->isReferenceType() && "Reference types were handled above");
2143
2144 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002145 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002146 // of P for type deduction; otherwise,
2147 if (P->isArrayType())
2148 P = Context.getArrayDecayedType(P);
2149 // - If P is a function type, the pointer type produced by the
2150 // function-to-pointer standard conversion (4.3) is used in
2151 // place of P for type deduction; otherwise,
2152 else if (P->isFunctionType())
2153 P = Context.getPointerType(P);
2154 // - If P is a cv-qualified type, the top level cv-qualifiers of
2155 // P’s type are ignored for type deduction.
2156 else
2157 P = P.getUnqualifiedType();
2158
2159 // C++0x [temp.deduct.conv]p3:
2160 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2161 // type are ignored for type deduction.
2162 A = A.getUnqualifiedType();
2163 }
2164
2165 // Template argument deduction for function templates in a SFINAE context.
2166 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002168
2169 // C++ [temp.deduct.conv]p1:
2170 // Template argument deduction is done by comparing the return
2171 // type of the template conversion function (call it P) with the
2172 // type that is required as the result of the conversion (call it
2173 // A) as described in 14.8.2.4.
2174 TemplateParameterList *TemplateParams
2175 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002176 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002177 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002178
2179 // C++0x [temp.deduct.conv]p4:
2180 // In general, the deduction process attempts to find template
2181 // argument values that will make the deduced A identical to
2182 // A. However, there are two cases that allow a difference:
2183 unsigned TDF = 0;
2184 // - If the original A is a reference type, A can be more
2185 // cv-qualified than the deduced A (i.e., the type referred to
2186 // by the reference)
2187 if (ToType->isReferenceType())
2188 TDF |= TDF_ParamWithReferenceType;
2189 // - The deduced A can be another pointer or pointer to member
2190 // type that can be converted to A via a qualification
2191 // conversion.
2192 //
2193 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2194 // both P and A are pointers or member pointers. In this case, we
2195 // just ignore cv-qualifiers completely).
2196 if ((P->isPointerType() && A->isPointerType()) ||
2197 (P->isMemberPointerType() && P->isMemberPointerType()))
2198 TDF |= TDF_IgnoreQualifiers;
2199 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002200 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002201 P, A, Info, Deduced, TDF))
2202 return Result;
2203
2204 // FIXME: we need to check that the deduced A is the same as A,
2205 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002207 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002208 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002209 FunctionDecl *Spec = 0;
2210 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002211 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2212 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002213 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2214 return Result;
2215}
2216
Douglas Gregor4b52e252009-12-21 23:17:24 +00002217/// \brief Deduce template arguments for a function template when there is
2218/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2219///
2220/// \param FunctionTemplate the function template for which we are performing
2221/// template argument deduction.
2222///
2223/// \param ExplicitTemplateArguments the explicitly-specified template
2224/// arguments.
2225///
2226/// \param Specialization if template argument deduction was successful,
2227/// this will be set to the function template specialization produced by
2228/// template argument deduction.
2229///
2230/// \param Info the argument will be updated to provide additional information
2231/// about template argument deduction.
2232///
2233/// \returns the result of template argument deduction.
2234Sema::TemplateDeductionResult
2235Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2236 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2237 FunctionDecl *&Specialization,
2238 TemplateDeductionInfo &Info) {
2239 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2240 QualType(), Specialization, Info);
2241}
2242
Douglas Gregor8a514912009-09-14 18:39:43 +00002243/// \brief Stores the result of comparing the qualifiers of two types.
2244enum DeductionQualifierComparison {
2245 NeitherMoreQualified = 0,
2246 ParamMoreQualified,
2247 ArgMoreQualified
2248};
2249
2250/// \brief Deduce the template arguments during partial ordering by comparing
2251/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2252///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002253/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002254///
2255/// \param TemplateParams the template parameters that we are deducing
2256///
2257/// \param ParamIn the parameter type
2258///
2259/// \param ArgIn the argument type
2260///
2261/// \param Info information about the template argument deduction itself
2262///
2263/// \param Deduced the deduced template arguments
2264///
2265/// \returns the result of template argument deduction so far. Note that a
2266/// "success" result means that template argument deduction has not yet failed,
2267/// but it may still fail, later, for other reasons.
2268static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002269DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002270 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002271 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002272 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002273 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2274 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002275 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2276 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002277
2278 // C++0x [temp.deduct.partial]p5:
2279 // Before the partial ordering is done, certain transformations are
2280 // performed on the types used for partial ordering:
2281 // - If P is a reference type, P is replaced by the type referred to.
2282 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002283 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002284 Param = ParamRef->getPointeeType();
2285
2286 // - If A is a reference type, A is replaced by the type referred to.
2287 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002288 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002289 Arg = ArgRef->getPointeeType();
2290
John McCalle27ec8a2009-10-23 23:03:21 +00002291 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002292 // C++0x [temp.deduct.partial]p6:
2293 // If both P and A were reference types (before being replaced with the
2294 // type referred to above), determine which of the two types (if any) is
2295 // more cv-qualified than the other; otherwise the types are considered to
2296 // be equally cv-qualified for partial ordering purposes. The result of this
2297 // determination will be used below.
2298 //
2299 // We save this information for later, using it only when deduction
2300 // succeeds in both directions.
2301 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2302 if (Param.isMoreQualifiedThan(Arg))
2303 QualifierResult = ParamMoreQualified;
2304 else if (Arg.isMoreQualifiedThan(Param))
2305 QualifierResult = ArgMoreQualified;
2306 QualifierComparisons->push_back(QualifierResult);
2307 }
2308
2309 // C++0x [temp.deduct.partial]p7:
2310 // Remove any top-level cv-qualifiers:
2311 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2312 // version of P.
2313 Param = Param.getUnqualifiedType();
2314 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2315 // version of A.
2316 Arg = Arg.getUnqualifiedType();
2317
2318 // C++0x [temp.deduct.partial]p8:
2319 // Using the resulting types P and A the deduction is then done as
2320 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2321 // from the argument template is considered to be at least as specialized
2322 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002323 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002324 Deduced, TDF_None);
2325}
2326
2327static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002328MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2329 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002330 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002331 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002332
2333/// \brief If this is a non-static member function,
2334static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2335 CXXMethodDecl *Method,
2336 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2337 if (Method->isStatic())
2338 return;
2339
2340 // C++ [over.match.funcs]p4:
2341 //
2342 // For non-static member functions, the type of the implicit
2343 // object parameter is
2344 // — "lvalue reference to cv X" for functions declared without a
2345 // ref-qualifier or with the & ref-qualifier
2346 // - "rvalue reference to cv X" for functions declared with the
2347 // && ref-qualifier
2348 //
2349 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2350 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2351 ArgTy = Context.getQualifiedType(ArgTy,
2352 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2353 ArgTy = Context.getLValueReferenceType(ArgTy);
2354 ArgTypes.push_back(ArgTy);
2355}
2356
Douglas Gregor8a514912009-09-14 18:39:43 +00002357/// \brief Determine whether the function template \p FT1 is at least as
2358/// specialized as \p FT2.
2359static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002360 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002361 FunctionTemplateDecl *FT1,
2362 FunctionTemplateDecl *FT2,
2363 TemplatePartialOrderingContext TPOC,
2364 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2365 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2366 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2367 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2368 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2369
2370 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2371 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002372 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002373 Deduced.resize(TemplateParams->size());
2374
2375 // C++0x [temp.deduct.partial]p3:
2376 // The types used to determine the ordering depend on the context in which
2377 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002378 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002379 CXXMethodDecl *Method1 = 0;
2380 CXXMethodDecl *Method2 = 0;
2381 bool IsNonStatic2 = false;
2382 bool IsNonStatic1 = false;
2383 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002384 switch (TPOC) {
2385 case TPOC_Call: {
2386 // - In the context of a function call, the function parameter types are
2387 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002388 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2389 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2390 IsNonStatic1 = Method1 && !Method1->isStatic();
2391 IsNonStatic2 = Method2 && !Method2->isStatic();
2392
2393 // C++0x [temp.func.order]p3:
2394 // [...] If only one of the function templates is a non-static
2395 // member, that function template is considered to have a new
2396 // first parameter inserted in its function parameter list. The
2397 // new parameter is of type "reference to cv A," where cv are
2398 // the cv-qualifiers of the function template (if any) and A is
2399 // the class of which the function template is a member.
2400 //
2401 // C++98/03 doesn't have this provision, so instead we drop the
2402 // first argument of the free function or static member, which
2403 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002404 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002405 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2406 IsNonStatic2 && !IsNonStatic1;
2407 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002408 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2409 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002410 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002411
2412 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002413 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2414 IsNonStatic1 && !IsNonStatic2;
2415 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002416 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2417 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002418 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002419
2420 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002421 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002422 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002423 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002424 Args2[I],
2425 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002426 Info,
2427 Deduced,
2428 QualifierComparisons))
2429 return false;
2430
2431 break;
2432 }
2433
2434 case TPOC_Conversion:
2435 // - In the context of a call to a conversion operator, the return types
2436 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002437 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002438 TemplateParams,
2439 Proto2->getResultType(),
2440 Proto1->getResultType(),
2441 Info,
2442 Deduced,
2443 QualifierComparisons))
2444 return false;
2445 break;
2446
2447 case TPOC_Other:
2448 // - In other contexts (14.6.6.2) the function template’s function type
2449 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002450 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002451 TemplateParams,
2452 FD2->getType(),
2453 FD1->getType(),
2454 Info,
2455 Deduced,
2456 QualifierComparisons))
2457 return false;
2458 break;
2459 }
2460
2461 // C++0x [temp.deduct.partial]p11:
2462 // In most cases, all template parameters must have values in order for
2463 // deduction to succeed, but for partial ordering purposes a template
2464 // parameter may remain without a value provided it is not used in the
2465 // types being used for partial ordering. [ Note: a template parameter used
2466 // in a non-deduced context is considered used. -end note]
2467 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2468 for (; ArgIdx != NumArgs; ++ArgIdx)
2469 if (Deduced[ArgIdx].isNull())
2470 break;
2471
2472 if (ArgIdx == NumArgs) {
2473 // All template arguments were deduced. FT1 is at least as specialized
2474 // as FT2.
2475 return true;
2476 }
2477
Douglas Gregore73bb602009-09-14 21:25:05 +00002478 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002479 llvm::SmallVector<bool, 4> UsedParameters;
2480 UsedParameters.resize(TemplateParams->size());
2481 switch (TPOC) {
2482 case TPOC_Call: {
2483 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002484 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2485 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2486 TemplateParams->getDepth(), UsedParameters);
2487 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002488 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2489 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002490 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002491 break;
2492 }
2493
2494 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002495 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2496 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002497 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002498 break;
2499
2500 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002501 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2502 TemplateParams->getDepth(),
2503 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002504 break;
2505 }
2506
2507 for (; ArgIdx != NumArgs; ++ArgIdx)
2508 // If this argument had no value deduced but was used in one of the types
2509 // used for partial ordering, then deduction fails.
2510 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2511 return false;
2512
2513 return true;
2514}
2515
2516
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002517/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002518/// to the rules of function template partial ordering (C++ [temp.func.order]).
2519///
2520/// \param FT1 the first function template
2521///
2522/// \param FT2 the second function template
2523///
Douglas Gregor8a514912009-09-14 18:39:43 +00002524/// \param TPOC the context in which we are performing partial ordering of
2525/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002526///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002527/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002528/// template is more specialized, returns NULL.
2529FunctionTemplateDecl *
2530Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2531 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002532 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002533 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002534 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002535 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2536 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002537 &QualifierComparisons);
2538
2539 if (Better1 != Better2) // We have a clear winner
2540 return Better1? FT1 : FT2;
2541
2542 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002543 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002544
2545
2546 // C++0x [temp.deduct.partial]p10:
2547 // If for each type being considered a given template is at least as
2548 // specialized for all types and more specialized for some set of types and
2549 // the other template is not more specialized for any types or is not at
2550 // least as specialized for any types, then the given template is more
2551 // specialized than the other template. Otherwise, neither template is more
2552 // specialized than the other.
2553 Better1 = false;
2554 Better2 = false;
2555 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2556 // C++0x [temp.deduct.partial]p9:
2557 // If, for a given type, deduction succeeds in both directions (i.e., the
2558 // types are identical after the transformations above) and if the type
2559 // from the argument template is more cv-qualified than the type from the
2560 // parameter template (as described above) that type is considered to be
2561 // more specialized than the other. If neither type is more cv-qualified
2562 // than the other then neither type is more specialized than the other.
2563 switch (QualifierComparisons[I]) {
2564 case NeitherMoreQualified:
2565 break;
2566
2567 case ParamMoreQualified:
2568 Better1 = true;
2569 if (Better2)
2570 return 0;
2571 break;
2572
2573 case ArgMoreQualified:
2574 Better2 = true;
2575 if (Better1)
2576 return 0;
2577 break;
2578 }
2579 }
2580
2581 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002582 if (Better1)
2583 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002584 else if (Better2)
2585 return FT2;
2586 else
2587 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002588}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002589
Douglas Gregord5a423b2009-09-25 18:43:00 +00002590/// \brief Determine if the two templates are equivalent.
2591static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2592 if (T1 == T2)
2593 return true;
2594
2595 if (!T1 || !T2)
2596 return false;
2597
2598 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2599}
2600
2601/// \brief Retrieve the most specialized of the given function template
2602/// specializations.
2603///
John McCallc373d482010-01-27 01:50:18 +00002604/// \param SpecBegin the start iterator of the function template
2605/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002606///
John McCallc373d482010-01-27 01:50:18 +00002607/// \param SpecEnd the end iterator of the function template
2608/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002609///
2610/// \param TPOC the partial ordering context to use to compare the function
2611/// template specializations.
2612///
2613/// \param Loc the location where the ambiguity or no-specializations
2614/// diagnostic should occur.
2615///
2616/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2617/// no matching candidates.
2618///
2619/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2620/// occurs.
2621///
2622/// \param CandidateDiag partial diagnostic used for each function template
2623/// specialization that is a candidate in the ambiguous ordering. One parameter
2624/// in this diagnostic should be unbound, which will correspond to the string
2625/// describing the template arguments for the function template specialization.
2626///
2627/// \param Index if non-NULL and the result of this function is non-nULL,
2628/// receives the index corresponding to the resulting function template
2629/// specialization.
2630///
2631/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002632/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002633///
2634/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2635/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002636UnresolvedSetIterator
2637Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2638 UnresolvedSetIterator SpecEnd,
2639 TemplatePartialOrderingContext TPOC,
2640 SourceLocation Loc,
2641 const PartialDiagnostic &NoneDiag,
2642 const PartialDiagnostic &AmbigDiag,
2643 const PartialDiagnostic &CandidateDiag) {
2644 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002645 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002646 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002647 }
2648
John McCallc373d482010-01-27 01:50:18 +00002649 if (SpecBegin + 1 == SpecEnd)
2650 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002651
2652 // Find the function template that is better than all of the templates it
2653 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002654 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002655 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002656 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002657 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002658 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2659 FunctionTemplateDecl *Challenger
2660 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002661 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002662 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002663 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002664 Challenger)) {
2665 Best = I;
2666 BestTemplate = Challenger;
2667 }
2668 }
2669
2670 // Make sure that the "best" function template is more specialized than all
2671 // of the others.
2672 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002673 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2674 FunctionTemplateDecl *Challenger
2675 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002676 if (I != Best &&
2677 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002678 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002679 BestTemplate)) {
2680 Ambiguous = true;
2681 break;
2682 }
2683 }
2684
2685 if (!Ambiguous) {
2686 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002687 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002688 }
2689
2690 // Diagnose the ambiguity.
2691 Diag(Loc, AmbigDiag);
2692
2693 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002694 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2695 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002696 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002697 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2698 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002699
John McCallc373d482010-01-27 01:50:18 +00002700 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002701}
2702
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002703/// \brief Returns the more specialized class template partial specialization
2704/// according to the rules of partial ordering of class template partial
2705/// specializations (C++ [temp.class.order]).
2706///
2707/// \param PS1 the first class template partial specialization
2708///
2709/// \param PS2 the second class template partial specialization
2710///
2711/// \returns the more specialized class template partial specialization. If
2712/// neither partial specialization is more specialized, returns NULL.
2713ClassTemplatePartialSpecializationDecl *
2714Sema::getMoreSpecializedPartialSpecialization(
2715 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002716 ClassTemplatePartialSpecializationDecl *PS2,
2717 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002718 // C++ [temp.class.order]p1:
2719 // For two class template partial specializations, the first is at least as
2720 // specialized as the second if, given the following rewrite to two
2721 // function templates, the first function template is at least as
2722 // specialized as the second according to the ordering rules for function
2723 // templates (14.6.6.2):
2724 // - the first function template has the same template parameters as the
2725 // first partial specialization and has a single function parameter
2726 // whose type is a class template specialization with the template
2727 // arguments of the first partial specialization, and
2728 // - the second function template has the same template parameters as the
2729 // second partial specialization and has a single function parameter
2730 // whose type is a class template specialization with the template
2731 // arguments of the second partial specialization.
2732 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002733 // Rather than synthesize function templates, we merely perform the
2734 // equivalent partial ordering by performing deduction directly on
2735 // the template arguments of the class template partial
2736 // specializations. This computation is slightly simpler than the
2737 // general problem of function template partial ordering, because
2738 // class template partial specializations are more constrained. We
2739 // know that every template parameter is deducible from the class
2740 // template partial specialization's template arguments, for
2741 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002742 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002743 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002744
2745 QualType PT1 = PS1->getInjectedSpecializationType();
2746 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002747
2748 // Determine whether PS1 is at least as specialized as PS2
2749 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002750 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002751 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002752 PT2,
2753 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002754 Info,
2755 Deduced,
2756 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002757 if (Better1) {
2758 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2759 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002760 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2761 PS1->getTemplateArgs(),
2762 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002763 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002764
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002765 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002766 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002767 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002768 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002769 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002770 PT1,
2771 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002772 Info,
2773 Deduced,
2774 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002775 if (Better2) {
2776 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2777 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002778 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2779 PS2->getTemplateArgs(),
2780 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002781 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002782
2783 if (Better1 == Better2)
2784 return 0;
2785
2786 return Better1? PS1 : PS2;
2787}
2788
Mike Stump1eb44332009-09-09 15:08:12 +00002789static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002790MarkUsedTemplateParameters(Sema &SemaRef,
2791 const TemplateArgument &TemplateArg,
2792 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002793 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002794 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002795
Douglas Gregore73bb602009-09-14 21:25:05 +00002796/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002797/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002798static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002799MarkUsedTemplateParameters(Sema &SemaRef,
2800 const Expr *E,
2801 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002802 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002803 llvm::SmallVectorImpl<bool> &Used) {
2804 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2805 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002806 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002807 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002808 return;
2809
Mike Stump1eb44332009-09-09 15:08:12 +00002810 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002811 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2812 if (!NTTP)
2813 return;
2814
Douglas Gregored9c0f92009-10-29 00:04:11 +00002815 if (NTTP->getDepth() == Depth)
2816 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002817}
2818
Douglas Gregore73bb602009-09-14 21:25:05 +00002819/// \brief Mark the template parameters that are used by the given
2820/// nested name specifier.
2821static void
2822MarkUsedTemplateParameters(Sema &SemaRef,
2823 NestedNameSpecifier *NNS,
2824 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002825 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002826 llvm::SmallVectorImpl<bool> &Used) {
2827 if (!NNS)
2828 return;
2829
Douglas Gregored9c0f92009-10-29 00:04:11 +00002830 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2831 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002832 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002833 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002834}
2835
2836/// \brief Mark the template parameters that are used by the given
2837/// template name.
2838static void
2839MarkUsedTemplateParameters(Sema &SemaRef,
2840 TemplateName Name,
2841 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002842 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002843 llvm::SmallVectorImpl<bool> &Used) {
2844 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2845 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00002846 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2847 if (TTP->getDepth() == Depth)
2848 Used[TTP->getIndex()] = true;
2849 }
Douglas Gregore73bb602009-09-14 21:25:05 +00002850 return;
2851 }
2852
Douglas Gregor788cd062009-11-11 01:00:40 +00002853 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2854 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2855 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002856 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00002857 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2858 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002859}
2860
2861/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002862/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002863static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002864MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2865 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002866 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002867 llvm::SmallVectorImpl<bool> &Used) {
2868 if (T.isNull())
2869 return;
2870
Douglas Gregor031a5882009-06-13 00:26:55 +00002871 // Non-dependent types have nothing deducible
2872 if (!T->isDependentType())
2873 return;
2874
2875 T = SemaRef.Context.getCanonicalType(T);
2876 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002877 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002878 MarkUsedTemplateParameters(SemaRef,
2879 cast<PointerType>(T)->getPointeeType(),
2880 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002881 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002882 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002883 break;
2884
2885 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002886 MarkUsedTemplateParameters(SemaRef,
2887 cast<BlockPointerType>(T)->getPointeeType(),
2888 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002889 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002890 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002891 break;
2892
2893 case Type::LValueReference:
2894 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00002895 MarkUsedTemplateParameters(SemaRef,
2896 cast<ReferenceType>(T)->getPointeeType(),
2897 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002898 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002899 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002900 break;
2901
2902 case Type::MemberPointer: {
2903 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00002904 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002905 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002906 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002907 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002908 break;
2909 }
2910
2911 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002912 MarkUsedTemplateParameters(SemaRef,
2913 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002914 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002915 // Fall through to check the element type
2916
2917 case Type::ConstantArray:
2918 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002919 MarkUsedTemplateParameters(SemaRef,
2920 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002921 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002922 break;
2923
2924 case Type::Vector:
2925 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00002926 MarkUsedTemplateParameters(SemaRef,
2927 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002928 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002929 break;
2930
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002931 case Type::DependentSizedExtVector: {
2932 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002933 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002934 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002935 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002936 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002937 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002938 break;
2939 }
2940
Douglas Gregor031a5882009-06-13 00:26:55 +00002941 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002942 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002943 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002944 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002945 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00002946 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002947 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002948 break;
2949 }
2950
Douglas Gregored9c0f92009-10-29 00:04:11 +00002951 case Type::TemplateTypeParm: {
2952 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
2953 if (TTP->getDepth() == Depth)
2954 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002955 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002956 }
Douglas Gregor031a5882009-06-13 00:26:55 +00002957
John McCall31f17ec2010-04-27 00:57:59 +00002958 case Type::InjectedClassName:
2959 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2960 // fall through
2961
Douglas Gregor031a5882009-06-13 00:26:55 +00002962 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00002963 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002964 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002965 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002966 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002967 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002968 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2969 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002970 break;
2971 }
2972
Douglas Gregore73bb602009-09-14 21:25:05 +00002973 case Type::Complex:
2974 if (!OnlyDeduced)
2975 MarkUsedTemplateParameters(SemaRef,
2976 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002977 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002978 break;
2979
Douglas Gregor4714c122010-03-31 17:34:00 +00002980 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00002981 if (!OnlyDeduced)
2982 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00002983 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002984 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002985 break;
2986
John McCall33500952010-06-11 00:33:02 +00002987 case Type::DependentTemplateSpecialization: {
2988 const DependentTemplateSpecializationType *Spec
2989 = cast<DependentTemplateSpecializationType>(T);
2990 if (!OnlyDeduced)
2991 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
2992 OnlyDeduced, Depth, Used);
2993 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2994 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2995 Used);
2996 break;
2997 }
2998
John McCallad5e7382010-03-01 23:49:17 +00002999 case Type::TypeOf:
3000 if (!OnlyDeduced)
3001 MarkUsedTemplateParameters(SemaRef,
3002 cast<TypeOfType>(T)->getUnderlyingType(),
3003 OnlyDeduced, Depth, Used);
3004 break;
3005
3006 case Type::TypeOfExpr:
3007 if (!OnlyDeduced)
3008 MarkUsedTemplateParameters(SemaRef,
3009 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3010 OnlyDeduced, Depth, Used);
3011 break;
3012
3013 case Type::Decltype:
3014 if (!OnlyDeduced)
3015 MarkUsedTemplateParameters(SemaRef,
3016 cast<DecltypeType>(T)->getUnderlyingExpr(),
3017 OnlyDeduced, Depth, Used);
3018 break;
3019
Douglas Gregor7536dd52010-12-20 02:24:11 +00003020 case Type::PackExpansion:
3021 MarkUsedTemplateParameters(SemaRef,
3022 cast<PackExpansionType>(T)->getPattern(),
3023 OnlyDeduced, Depth, Used);
3024 break;
3025
Douglas Gregore73bb602009-09-14 21:25:05 +00003026 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003027 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003028 case Type::VariableArray:
3029 case Type::FunctionNoProto:
3030 case Type::Record:
3031 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003032 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003033 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003034 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003035 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003036#define TYPE(Class, Base)
3037#define ABSTRACT_TYPE(Class, Base)
3038#define DEPENDENT_TYPE(Class, Base)
3039#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3040#include "clang/AST/TypeNodes.def"
3041 break;
3042 }
3043}
3044
Douglas Gregore73bb602009-09-14 21:25:05 +00003045/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003046/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003047static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003048MarkUsedTemplateParameters(Sema &SemaRef,
3049 const TemplateArgument &TemplateArg,
3050 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003051 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003052 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003053 switch (TemplateArg.getKind()) {
3054 case TemplateArgument::Null:
3055 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003056 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003057 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Douglas Gregor031a5882009-06-13 00:26:55 +00003059 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003060 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003061 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003062 break;
3063
Douglas Gregor788cd062009-11-11 01:00:40 +00003064 case TemplateArgument::Template:
3065 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
3066 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003067 break;
3068
3069 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003070 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003071 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003072 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003073
Anders Carlssond01b1da2009-06-15 17:04:53 +00003074 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003075 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3076 PEnd = TemplateArg.pack_end();
3077 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003078 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003079 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003080 }
3081}
3082
3083/// \brief Mark the template parameters can be deduced by the given
3084/// template argument list.
3085///
3086/// \param TemplateArgs the template argument list from which template
3087/// parameters will be deduced.
3088///
3089/// \param Deduced a bit vector whose elements will be set to \c true
3090/// to indicate when the corresponding template parameter will be
3091/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003092void
Douglas Gregore73bb602009-09-14 21:25:05 +00003093Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003094 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003095 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003096 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003097 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3098 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003099}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003100
3101/// \brief Marks all of the template parameters that will be deduced by a
3102/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003103void
3104Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3105 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003106 TemplateParameterList *TemplateParams
3107 = FunctionTemplate->getTemplateParameters();
3108 Deduced.clear();
3109 Deduced.resize(TemplateParams->size());
3110
3111 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3112 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3113 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003114 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003115}