blob: 5d543e9e75885242d99f5bd036e37cfeb7c30d56 [file] [log] [blame]
Douglas Gregor55ca8f62009-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
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-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 Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-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.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
61}
62
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor63814022011-01-21 17:29:42 +000094/// \brief Whether template argument deduction for two reference parameters
95/// resulted in the argument type, parameter type, or neither type being more
96/// qualified than the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000097enum DeductionQualifierComparison {
98 NeitherMoreQualified = 0,
99 ParamMoreQualified,
100 ArgMoreQualified
Douglas Gregorb837ea42011-01-11 17:34:58 +0000101};
102
Douglas Gregor63814022011-01-21 17:29:42 +0000103/// \brief Stores the result of comparing two reference parameters while
104/// performing template argument deduction for partial ordering of function
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105/// templates.
Douglas Gregor63814022011-01-21 17:29:42 +0000106struct RefParamPartialOrderingComparison {
107 /// \brief Whether the parameter type is an rvalue reference type.
108 bool ParamIsRvalueRef;
109 /// \brief Whether the argument type is an rvalue reference type.
110 bool ArgIsRvalueRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000111
Douglas Gregor63814022011-01-21 17:29:42 +0000112 /// \brief Whether the parameter or argument (or neither) is more qualified.
113 DeductionQualifierComparison Qualifiers;
114};
115
116
Douglas Gregorb837ea42011-01-11 17:34:58 +0000117
Douglas Gregor7baabef2010-12-22 18:17:10 +0000118static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000119DeduceTemplateArgumentsByTypeMatch(Sema &S,
120 TemplateParameterList *TemplateParams,
121 QualType Param,
122 QualType Arg,
123 TemplateDeductionInfo &Info,
124 SmallVectorImpl<DeducedTemplateArgument> &
125 Deduced,
126 unsigned TDF,
127 bool PartialOrdering = false,
128 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000129 RefParamComparisons = nullptr);
Douglas Gregor5499af42011-01-05 23:12:31 +0000130
131static Sema::TemplateDeductionResult
132DeduceTemplateArguments(Sema &S,
133 TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000134 const TemplateArgument *Params, unsigned NumParams,
135 const TemplateArgument *Args, unsigned NumArgs,
136 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +0000137 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000138
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000139/// \brief If the given expression is of a form that permits the deduction
140/// of a non-type template parameter, return the declaration of that
141/// non-type template parameter.
142static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000143 // If we are within an alias template, the expression may have undergone
144 // any number of parameter substitutions already.
145 while (1) {
146 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
147 E = IC->getSubExpr();
148 else if (SubstNonTypeTemplateParmExpr *Subst =
149 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
150 E = Subst->getReplacement();
151 else
152 break;
153 }
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
156 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000157
Craig Topperc3ec1492014-05-26 06:22:03 +0000158 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000159}
160
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000161/// \brief Determine whether two declaration pointers refer to the same
162/// declaration.
163static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000164 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
165 X = NX->getUnderlyingDecl();
166 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
167 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000168
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000169 return X->getCanonicalDecl() == Y->getCanonicalDecl();
170}
171
172/// \brief Verify that the given, deduced template arguments are compatible.
173///
174/// \returns The deduced template argument, or a NULL template argument if
175/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000177checkDeducedTemplateArguments(ASTContext &Context,
178 const DeducedTemplateArgument &X,
179 const DeducedTemplateArgument &Y) {
180 // We have no deduction for one or both of the arguments; they're compatible.
181 if (X.isNull())
182 return Y;
183 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000185
186 switch (X.getKind()) {
187 case TemplateArgument::Null:
188 llvm_unreachable("Non-deduced template arguments handled above");
189
190 case TemplateArgument::Type:
191 // If two template type arguments have the same type, they're compatible.
192 if (Y.getKind() == TemplateArgument::Type &&
193 Context.hasSameType(X.getAsType(), Y.getAsType()))
194 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000198 case TemplateArgument::Integral:
199 // If we deduced a constant in one case and either a dependent expression or
200 // declaration in another case, keep the integral constant.
201 // If both are integral constants with the same value, keep that value.
202 if (Y.getKind() == TemplateArgument::Expression ||
203 Y.getKind() == TemplateArgument::Declaration ||
204 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000205 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000206 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207 X.wasDeducedFromArrayBound() &&
208 Y.wasDeducedFromArrayBound());
209
210 // All other combinations are incompatible.
211 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213 case TemplateArgument::Template:
214 if (Y.getKind() == TemplateArgument::Template &&
215 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
216 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000217
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000218 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220
221 case TemplateArgument::TemplateExpansion:
222 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000224 Y.getAsTemplateOrTemplatePattern()))
225 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000227 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000229
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000230 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000231 // If we deduced a dependent expression in one case and either an integral
232 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000233 // or declaration.
234 if (Y.getKind() == TemplateArgument::Integral ||
235 Y.getKind() == TemplateArgument::Declaration)
236 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
237 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000238
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000239 if (Y.getKind() == TemplateArgument::Expression) {
240 // Compare the expressions for equality
241 llvm::FoldingSetNodeID ID1, ID2;
242 X.getAsExpr()->Profile(ID1, Context, true);
243 Y.getAsExpr()->Profile(ID2, Context, true);
244 if (ID1 == ID2)
245 return X;
246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000247
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000248 // All other combinations are incompatible.
249 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000250
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000251 case TemplateArgument::Declaration:
252 // If we deduced a declaration and a dependent expression, keep the
253 // declaration.
254 if (Y.getKind() == TemplateArgument::Expression)
255 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000257 // If we deduced a declaration and an integral constant, keep the
258 // integral constant.
259 if (Y.getKind() == TemplateArgument::Integral)
260 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000261
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000262 // If we deduced two declarations, make sure they they refer to the
263 // same declaration.
264 if (Y.getKind() == TemplateArgument::Declaration &&
Eli Friedmanb826a002012-09-26 02:36:12 +0000265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
266 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam())
267 return X;
268
269 // All other combinations are incompatible.
270 return DeducedTemplateArgument();
271
272 case TemplateArgument::NullPtr:
273 // If we deduced a null pointer and a dependent expression, keep the
274 // null pointer.
275 if (Y.getKind() == TemplateArgument::Expression)
276 return X;
277
278 // If we deduced a null pointer and an integral constant, keep the
279 // integral constant.
280 if (Y.getKind() == TemplateArgument::Integral)
281 return Y;
282
283 // If we deduced two null pointers, make sure they have the same type.
284 if (Y.getKind() == TemplateArgument::NullPtr &&
285 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000288 // All other combinations are incompatible.
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000291 case TemplateArgument::Pack:
292 if (Y.getKind() != TemplateArgument::Pack ||
293 X.pack_size() != Y.pack_size())
294 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
296 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 XAEnd = X.pack_end(),
298 YA = Y.pack_begin();
299 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000300 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 if (checkDeducedTemplateArguments(Context,
302 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000303 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
304 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000305 return DeducedTemplateArgument();
306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 return X;
309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
David Blaikiee4d798f2012-01-20 21:50:17 +0000311 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000312}
313
Mike Stump11289f42009-09-09 15:08:12 +0000314/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000315/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000316static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000317DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000318 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000319 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000320 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000321 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000322 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000323 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000324 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000325
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000326 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
327 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Deduced[NTTP->getIndex()],
330 NewDeduced);
331 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000332 Info.Param = NTTP;
333 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000334 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000335 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000338 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000339 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000340}
341
Mike Stump11289f42009-09-09 15:08:12 +0000342/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000343/// from the given type- or value-dependent expression.
344///
345/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000346static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000347DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000348 NonTypeTemplateParmDecl *NTTP,
349 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000350 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000351 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000352 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000353 "Cannot deduce non-type template argument with depth > 0");
354 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
355 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000357 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
359 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000360 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000362 if (Result.isNull()) {
363 Info.Param = NTTP;
364 Info.FirstArg = Deduced[NTTP->getIndex()];
365 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000369 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000370 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000371}
372
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000373/// \brief Deduce the value of the given non-type template parameter
374/// from the given declaration.
375///
376/// \returns true if deduction succeeded, false otherwise.
377static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000378DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000379 NonTypeTemplateParmDecl *NTTP,
380 ValueDecl *D,
381 TemplateDeductionInfo &Info,
382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000383 assert(NTTP->getDepth() == 0 &&
384 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Craig Topperc3ec1492014-05-26 06:22:03 +0000386 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Eli Friedmanb826a002012-09-26 02:36:12 +0000387 TemplateArgument New(D, NTTP->getType()->isReferenceType());
388 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000390 Deduced[NTTP->getIndex()],
391 NewDeduced);
392 if (Result.isNull()) {
393 Info.Param = NTTP;
394 Info.FirstArg = Deduced[NTTP->getIndex()];
395 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000399 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000400 return Sema::TDK_Success;
401}
402
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000403static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000404DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000405 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000406 TemplateName Param,
407 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000408 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000409 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000410 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 if (!ParamDecl) {
412 // The parameter type is dependent and is not a template template parameter,
413 // so there is nothing that we can deduce.
414 return Sema::TDK_Success;
415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
Douglas Gregoradee3e32009-11-11 23:06:43 +0000417 if (TemplateTemplateParmDecl *TempParam
418 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000419 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000421 Deduced[TempParam->getIndex()],
422 NewDeduced);
423 if (Result.isNull()) {
424 Info.Param = TempParam;
425 Info.FirstArg = Deduced[TempParam->getIndex()];
426 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000430 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregoradee3e32009-11-11 23:06:43 +0000434 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000435 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregoradee3e32009-11-11 23:06:43 +0000438 // Mismatch of non-dependent template parameter to argument.
439 Info.FirstArg = TemplateArgument(Param);
440 Info.SecondArg = TemplateArgument(Arg);
441 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000445/// type (which is a template-id) with the template argument type.
446///
Chandler Carruthc1263112010-02-07 21:33:28 +0000447/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000448///
449/// \param TemplateParams the template parameters that we are deducing
450///
451/// \param Param the parameter type
452///
453/// \param Arg the argument type
454///
455/// \param Info information about the template argument deduction itself
456///
457/// \param Deduced the deduced template arguments
458///
459/// \returns the result of template argument deduction so far. Note that a
460/// "success" result means that template argument deduction has not yet failed,
461/// but it may still fail, later, for other reasons.
462static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000463DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000464 TemplateParameterList *TemplateParams,
465 const TemplateSpecializationType *Param,
466 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000467 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000468 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000469 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregore81f3e72009-07-07 23:09:34 +0000471 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000472 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000473 = dyn_cast<TemplateSpecializationType>(Arg)) {
474 // Perform template argument deduction for the template name.
475 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000476 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477 Param->getTemplateName(),
478 SpecArg->getTemplateName(),
479 Info, Deduced))
480 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000481
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000484 // argument. Ignore any missing/extra arguments, since they could be
485 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486 return DeduceTemplateArguments(S, TemplateParams,
487 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000488 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000489 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregore81f3e72009-07-07 23:09:34 +0000492 // If the argument type is a class template specialization, we
493 // perform template argument deduction using its template
494 // arguments.
495 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000496 if (!RecordArg) {
497 Info.FirstArg = TemplateArgument(QualType(Param, 0));
498 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000499 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
502 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000503 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 if (!SpecArg) {
505 Info.FirstArg = TemplateArgument(QualType(Param, 0));
506 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 // Perform template argument deduction for the template name.
511 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000512 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000513 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 Param->getTemplateName(),
515 TemplateName(SpecArg->getSpecializedTemplate()),
516 Info, Deduced))
517 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregor7baabef2010-12-22 18:17:10 +0000519 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000521 Param->getArgs(), Param->getNumArgs(),
522 SpecArg->getTemplateArgs().data(),
523 SpecArg->getTemplateArgs().size(),
524 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000525}
526
John McCall08569062010-08-28 22:14:41 +0000527/// \brief Determines whether the given type is an opaque type that
528/// might be more qualified when instantiated.
529static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
530 switch (T->getTypeClass()) {
531 case Type::TypeOfExpr:
532 case Type::TypeOf:
533 case Type::DependentName:
534 case Type::Decltype:
535 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000536 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000537 return true;
538
539 case Type::ConstantArray:
540 case Type::IncompleteArray:
541 case Type::VariableArray:
542 case Type::DependentSizedArray:
543 return IsPossiblyOpaquelyQualifiedType(
544 cast<ArrayType>(T)->getElementType());
545
546 default:
547 return false;
548 }
549}
550
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000551/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000553getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000554 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
555 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Douglas Gregor5499af42011-01-05 23:12:31 +0000557 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
558 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor5499af42011-01-05 23:12:31 +0000560 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
561 return std::make_pair(TTP->getDepth(), TTP->getIndex());
562}
563
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000564/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000566getDepthAndIndex(UnexpandedParameterPack UPP) {
567 if (const TemplateTypeParmType *TTP
568 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
569 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000571 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
572}
573
Douglas Gregor5499af42011-01-05 23:12:31 +0000574/// \brief Helper function to build a TemplateParameter when we don't
575/// know its type statically.
576static TemplateParameter makeTemplateParameter(Decl *D) {
577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
578 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000579 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000580 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor5499af42011-01-05 23:12:31 +0000582 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
583}
584
Richard Smith0a80d572014-05-29 01:12:14 +0000585/// A pack that we're currently deducing.
586struct clang::DeducedPack {
587 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000588
Richard Smith0a80d572014-05-29 01:12:14 +0000589 // The index of the pack.
590 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Richard Smith0a80d572014-05-29 01:12:14 +0000592 // The old value of the pack before we started deducing it.
593 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000594
Richard Smith0a80d572014-05-29 01:12:14 +0000595 // A deferred value of this pack from an inner deduction, that couldn't be
596 // deduced because this deduction hadn't happened yet.
597 DeducedTemplateArgument DeferredDeduction;
598
599 // The new value of the pack.
600 SmallVector<DeducedTemplateArgument, 4> New;
601
602 // The outer deduction for this pack, if any.
603 DeducedPack *Outer;
604};
605
606/// A scope in which we're performing pack deduction.
607class PackDeductionScope {
608public:
609 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
610 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
611 TemplateDeductionInfo &Info, TemplateArgument Pattern)
612 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
613 // Compute the set of template parameter indices that correspond to
614 // parameter packs expanded by the pack expansion.
615 {
616 llvm::SmallBitVector SawIndices(TemplateParams->size());
617 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
618 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
619 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
620 unsigned Depth, Index;
621 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
622 if (Depth == 0 && !SawIndices[Index]) {
623 SawIndices[Index] = true;
624
625 // Save the deduced template argument for the parameter pack expanded
626 // by this pack expansion, then clear out the deduction.
627 DeducedPack Pack(Index);
628 Pack.Saved = Deduced[Index];
629 Deduced[Index] = TemplateArgument();
630
631 Packs.push_back(Pack);
632 }
633 }
634 }
635 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
636
637 for (auto &Pack : Packs) {
638 if (Info.PendingDeducedPacks.size() > Pack.Index)
639 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
640 else
641 Info.PendingDeducedPacks.resize(Pack.Index + 1);
642 Info.PendingDeducedPacks[Pack.Index] = &Pack;
643
644 if (S.CurrentInstantiationScope) {
645 // If the template argument pack was explicitly specified, add that to
646 // the set of deduced arguments.
647 const TemplateArgument *ExplicitArgs;
648 unsigned NumExplicitArgs;
649 NamedDecl *PartiallySubstitutedPack =
650 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
651 &ExplicitArgs, &NumExplicitArgs);
652 if (PartiallySubstitutedPack &&
653 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
654 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
655 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000656 }
657 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000658
Richard Smith0a80d572014-05-29 01:12:14 +0000659 ~PackDeductionScope() {
660 for (auto &Pack : Packs)
661 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Richard Smith0a80d572014-05-29 01:12:14 +0000664 /// Move to deducing the next element in each pack that is being deduced.
665 void nextPackElement() {
666 // Capture the deduced template arguments for each parameter pack expanded
667 // by this pack expansion, add them to the list of arguments we've deduced
668 // for that pack, then clear out the deduced argument.
669 for (auto &Pack : Packs) {
670 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
671 if (!DeducedArg.isNull()) {
672 Pack.New.push_back(DeducedArg);
673 DeducedArg = DeducedTemplateArgument();
674 }
675 }
676 }
677
678 /// \brief Finish template argument deduction for a set of argument packs,
679 /// producing the argument packs and checking for consistency with prior
680 /// deductions.
681 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
682 // Build argument packs for each of the parameter packs expanded by this
683 // pack expansion.
684 for (auto &Pack : Packs) {
685 // Put back the old value for this pack.
686 Deduced[Pack.Index] = Pack.Saved;
687
688 // Build or find a new value for this pack.
689 DeducedTemplateArgument NewPack;
690 if (HasAnyArguments && Pack.New.empty()) {
691 if (Pack.DeferredDeduction.isNull()) {
692 // We were not able to deduce anything for this parameter pack
693 // (because it only appeared in non-deduced contexts), so just
694 // restore the saved argument pack.
695 continue;
696 }
697
698 NewPack = Pack.DeferredDeduction;
699 Pack.DeferredDeduction = TemplateArgument();
700 } else if (Pack.New.empty()) {
701 // If we deduced an empty argument pack, create it now.
702 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
703 } else {
704 TemplateArgument *ArgumentPack =
705 new (S.Context) TemplateArgument[Pack.New.size()];
706 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
707 NewPack = DeducedTemplateArgument(
708 TemplateArgument(ArgumentPack, Pack.New.size()),
709 Pack.New[0].wasDeducedFromArrayBound());
710 }
711
712 // Pick where we're going to put the merged pack.
713 DeducedTemplateArgument *Loc;
714 if (Pack.Outer) {
715 if (Pack.Outer->DeferredDeduction.isNull()) {
716 // Defer checking this pack until we have a complete pack to compare
717 // it against.
718 Pack.Outer->DeferredDeduction = NewPack;
719 continue;
720 }
721 Loc = &Pack.Outer->DeferredDeduction;
722 } else {
723 Loc = &Deduced[Pack.Index];
724 }
725
726 // Check the new pack matches any previous value.
727 DeducedTemplateArgument OldPack = *Loc;
728 DeducedTemplateArgument Result =
729 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
730
731 // If we deferred a deduction of this pack, check that one now too.
732 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
733 OldPack = Result;
734 NewPack = Pack.DeferredDeduction;
735 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
736 }
737
738 if (Result.isNull()) {
739 Info.Param =
740 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
741 Info.FirstArg = OldPack;
742 Info.SecondArg = NewPack;
743 return Sema::TDK_Inconsistent;
744 }
745
746 *Loc = Result;
747 }
748
749 return Sema::TDK_Success;
750 }
751
752private:
753 Sema &S;
754 TemplateParameterList *TemplateParams;
755 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
756 TemplateDeductionInfo &Info;
757
758 SmallVector<DeducedPack, 2> Packs;
759};
Douglas Gregorb94a6172011-01-10 17:53:52 +0000760
Douglas Gregor5499af42011-01-05 23:12:31 +0000761/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762/// types to the list of argument types, as in the parameter-type-lists of
763/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000764///
765/// \param S The semantic analysis object within which we are deducing
766///
767/// \param TemplateParams The template parameters that we are deducing
768///
769/// \param Params The list of parameter types
770///
771/// \param NumParams The number of types in \c Params
772///
773/// \param Args The list of argument types
774///
775/// \param NumArgs The number of types in \c Args
776///
777/// \param Info information about the template argument deduction itself
778///
779/// \param Deduced the deduced template arguments
780///
781/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
782/// how template argument deduction is performed.
783///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000784/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000785/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000786/// (C++0x [temp.deduct.partial]).
787///
Douglas Gregor63814022011-01-21 17:29:42 +0000788/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000789/// in the context of partial ordering, the set of qualifier comparisons.
790///
Douglas Gregor5499af42011-01-05 23:12:31 +0000791/// \returns the result of template argument deduction so far. Note that a
792/// "success" result means that template argument deduction has not yet failed,
793/// but it may still fail, later, for other reasons.
794static Sema::TemplateDeductionResult
795DeduceTemplateArguments(Sema &S,
796 TemplateParameterList *TemplateParams,
797 const QualType *Params, unsigned NumParams,
798 const QualType *Args, unsigned NumArgs,
799 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000800 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000801 unsigned TDF,
802 bool PartialOrdering = false,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000803 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 RefParamComparisons = nullptr) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000805 // Fast-path check to see if we have too many/too few arguments.
806 if (NumParams != NumArgs &&
807 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
808 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // Similarly, if P has a form that contains (T), then each parameter type
813 // Pi of the respective parameter-type- list of P is compared with the
814 // corresponding parameter type Ai of the corresponding parameter-type-list
815 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000816 unsigned ArgIdx = 0, ParamIdx = 0;
817 for (; ParamIdx != NumParams; ++ParamIdx) {
818 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000820 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
821 if (!Expansion) {
822 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // Make sure we have an argument.
825 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000826 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000828 if (isa<PackExpansionType>(Args[ArgIdx])) {
829 // C++0x [temp.deduct.type]p22:
830 // If the original function parameter associated with A is a function
831 // parameter pack and the function parameter associated with P is not
832 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000833 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor5499af42011-01-05 23:12:31 +0000836 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000837 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
838 Params[ParamIdx], Args[ArgIdx],
839 Info, Deduced, TDF,
840 PartialOrdering,
841 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000842 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor5499af42011-01-05 23:12:31 +0000844 ++ArgIdx;
845 continue;
846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000848 // C++0x [temp.deduct.type]p5:
849 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000851 // parameter-declaration-clause.
852 if (ParamIdx + 1 < NumParams)
853 return Sema::TDK_Success;
854
Douglas Gregor5499af42011-01-05 23:12:31 +0000855 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000857 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000858 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000859 // comparison deduces template arguments for subsequent positions in the
860 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000863 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 bool HasAnyArguments = false;
866 for (; ArgIdx < NumArgs; ++ArgIdx) {
867 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor5499af42011-01-05 23:12:31 +0000869 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000871 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
872 Args[ArgIdx], Info, Deduced,
873 TDF, PartialOrdering,
874 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Richard Smith0a80d572014-05-29 01:12:14 +0000877 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 // Build argument packs for each of the parameter packs expanded by this
881 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000882 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // Make sure we don't have any extra arguments.
887 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000888 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 return Sema::TDK_Success;
891}
892
Douglas Gregor1d684c22011-04-28 00:56:09 +0000893/// \brief Determine whether the parameter has qualifiers that are either
894/// inconsistent with or a superset of the argument's qualifiers.
895static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
896 QualType ArgType) {
897 Qualifiers ParamQs = ParamType.getQualifiers();
898 Qualifiers ArgQs = ArgType.getQualifiers();
899
900 if (ParamQs == ArgQs)
901 return false;
902
903 // Mismatched (but not missing) Objective-C GC attributes.
904 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
905 ParamQs.hasObjCGCAttr())
906 return true;
907
908 // Mismatched (but not missing) address spaces.
909 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
910 ParamQs.hasAddressSpace())
911 return true;
912
John McCall31168b02011-06-15 23:02:42 +0000913 // Mismatched (but not missing) Objective-C lifetime qualifiers.
914 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
915 ParamQs.hasObjCLifetime())
916 return true;
917
Douglas Gregor1d684c22011-04-28 00:56:09 +0000918 // CVR qualifier superset.
919 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
920 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
921 == ParamQs.getCVRQualifiers());
922}
923
Douglas Gregor19a41f12013-04-17 08:45:07 +0000924/// \brief Compare types for equality with respect to possibly compatible
925/// function types (noreturn adjustment, implicit calling conventions). If any
926/// of parameter and argument is not a function, just perform type comparison.
927///
928/// \param Param the template parameter type.
929///
930/// \param Arg the argument type.
931bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
932 CanQualType Arg) {
933 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
934 *ArgFunction = Arg->getAs<FunctionType>();
935
936 // Just compare if not functions.
937 if (!ParamFunction || !ArgFunction)
938 return Param == Arg;
939
940 // Noreturn adjustment.
941 QualType AdjustedParam;
942 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
943 return Arg == Context.getCanonicalType(AdjustedParam);
944
945 // FIXME: Compatible calling conventions.
946
947 return Param == Arg;
948}
949
Douglas Gregorcceb9752009-06-26 18:27:22 +0000950/// \brief Deduce the template arguments by comparing the parameter type and
951/// the argument type (C++ [temp.deduct.type]).
952///
Chandler Carruthc1263112010-02-07 21:33:28 +0000953/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000954///
955/// \param TemplateParams the template parameters that we are deducing
956///
957/// \param ParamIn the parameter type
958///
959/// \param ArgIn the argument type
960///
961/// \param Info information about the template argument deduction itself
962///
963/// \param Deduced the deduced template arguments
964///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000965/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000966/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000967///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000968/// \param PartialOrdering Whether we're performing template argument deduction
969/// in the context of partial ordering (C++0x [temp.deduct.partial]).
970///
Douglas Gregor63814022011-01-21 17:29:42 +0000971/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000972/// in the context of partial ordering, the set of qualifier comparisons.
973///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000974/// \returns the result of template argument deduction so far. Note that a
975/// "success" result means that template argument deduction has not yet failed,
976/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000977static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000978DeduceTemplateArgumentsByTypeMatch(Sema &S,
979 TemplateParameterList *TemplateParams,
980 QualType ParamIn, QualType ArgIn,
981 TemplateDeductionInfo &Info,
982 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
983 unsigned TDF,
984 bool PartialOrdering,
985 SmallVectorImpl<RefParamPartialOrderingComparison> *
986 RefParamComparisons) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000987 // We only want to look at the canonical types, since typedefs and
988 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000989 QualType Param = S.Context.getCanonicalType(ParamIn);
990 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000991
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000992 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000994 if (const PackExpansionType *ArgExpansion
995 = dyn_cast<PackExpansionType>(Arg))
996 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000997
Douglas Gregorb837ea42011-01-11 17:34:58 +0000998 if (PartialOrdering) {
999 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000 // Before the partial ordering is done, certain transformations are
1001 // performed on the types used for partial ordering:
1002 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001003 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1004 if (ParamRef)
1005 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregorb837ea42011-01-11 17:34:58 +00001007 // - If A is a reference type, A is replaced by the type referred to.
1008 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1009 if (ArgRef)
1010 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
Douglas Gregor63814022011-01-21 17:29:42 +00001012 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014 // If both P and A were reference types (before being replaced with the
1015 // type referred to above), determine which of the two types (if any) is
Douglas Gregorb837ea42011-01-11 17:34:58 +00001016 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001017 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregorb837ea42011-01-11 17:34:58 +00001018 // of this determination will be used below.
1019 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020 // We save this information for later, using it only when deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +00001021 // succeeds in both directions.
Douglas Gregor63814022011-01-21 17:29:42 +00001022 RefParamPartialOrderingComparison Comparison;
1023 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
1024 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
1025 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001026
1027 Qualifiers ParamQuals = Param.getQualifiers();
1028 Qualifiers ArgQuals = Arg.getQualifiers();
1029 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001030 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001031 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001032 Comparison.Qualifiers = ArgMoreQualified;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001033 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() &&
1034 ArgQuals.withoutObjCLifetime()
1035 == ParamQuals.withoutObjCLifetime()) {
1036 // Prefer binding to non-__unsafe_autoretained parameters.
1037 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1038 ParamQuals.getObjCLifetime())
1039 Comparison.Qualifiers = ParamMoreQualified;
1040 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1041 ArgQuals.getObjCLifetime())
1042 Comparison.Qualifiers = ArgMoreQualified;
1043 }
Douglas Gregor63814022011-01-21 17:29:42 +00001044 RefParamComparisons->push_back(Comparison);
Douglas Gregorb837ea42011-01-11 17:34:58 +00001045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregorb837ea42011-01-11 17:34:58 +00001047 // C++0x [temp.deduct.partial]p7:
1048 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001050 // version of P.
1051 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001053 // version of A.
1054 Arg = Arg.getUnqualifiedType();
1055 } else {
1056 // C++0x [temp.deduct.call]p4 bullet 1:
1057 // - If the original P is a reference type, the deduced A (i.e., the type
1058 // referred to by the reference) can be more cv-qualified than the
1059 // transformed A.
1060 if (TDF & TDF_ParamWithReferenceType) {
1061 Qualifiers Quals;
1062 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1063 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001064 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001065 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
Douglas Gregor85f240c2011-01-25 17:19:08 +00001068 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1069 // C++0x [temp.deduct.type]p10:
1070 // If P and A are function types that originated from deduction when
1071 // taking the address of a function template (14.8.2.2) or when deducing
1072 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073 // Ai are parameters of the top-level parameter-type-list of P and A,
1074 // respectively, Pi is adjusted if it is an rvalue reference to a
1075 // cv-unqualified template parameter and Ai is an lvalue reference, in
1076 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001077 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1078 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001079 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001080 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081
Douglas Gregor85f240c2011-01-25 17:19:08 +00001082 if (const RValueReferenceType *ParamRef
1083 = Param->getAs<RValueReferenceType>()) {
1084 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1085 !ParamRef->getPointeeType().getQualifiers())
1086 if (Arg->isLValueReferenceType())
1087 Param = ParamRef->getPointeeType();
1088 }
1089 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001092 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001093 // A template type argument T, a template template argument TT or a
1094 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001095 // the following forms:
1096 //
1097 // T
1098 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001100 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001101 // Just skip any attempts to deduce from a placeholder type.
1102 if (Arg->isPlaceholderType())
1103 return Sema::TDK_Success;
1104
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001105 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001106 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor60454822009-07-22 20:02:25 +00001108 // If the argument type is an array type, move the qualifiers up to the
1109 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001110 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001111 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001112 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001113 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001114 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001115 RecanonicalizeArg = true;
1116 }
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001119 // The argument type can not be less qualified than the parameter
1120 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001121 if (!(TDF & TDF_IgnoreQualifiers) &&
1122 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001123 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001124 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001125 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001126 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001127 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001128
1129 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001130 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001131 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001132
Douglas Gregor1d684c22011-04-28 00:56:09 +00001133 // Remove any qualifiers on the parameter from the deduced type.
1134 // We checked the qualifiers for consistency above.
1135 Qualifiers DeducedQs = DeducedType.getQualifiers();
1136 Qualifiers ParamQs = Param.getQualifiers();
1137 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1138 if (ParamQs.hasObjCGCAttr())
1139 DeducedQs.removeObjCGCAttr();
1140 if (ParamQs.hasAddressSpace())
1141 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001142 if (ParamQs.hasObjCLifetime())
1143 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001144
1145 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001146 // If template deduction would produce a lifetime qualifier on a type
1147 // that is not a lifetime type, template argument deduction fails.
1148 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1149 !DeducedType->isDependentType()) {
1150 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1151 Info.FirstArg = TemplateArgument(Param);
1152 Info.SecondArg = TemplateArgument(Arg);
1153 return Sema::TDK_Underqualified;
1154 }
1155
1156 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001157 // If template deduction would produce an argument type with lifetime type
1158 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001159 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001160 DeducedType->isObjCLifetimeType() &&
1161 !DeducedQs.hasObjCLifetime())
1162 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1163
Douglas Gregor1d684c22011-04-28 00:56:09 +00001164 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1165 DeducedQs);
1166
Douglas Gregord6605db2009-07-22 21:30:48 +00001167 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001168 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001170 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001171 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001172 Deduced[Index],
1173 NewDeduced);
1174 if (Result.isNull()) {
1175 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1176 Info.FirstArg = Deduced[Index];
1177 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001181 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001183 }
1184
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001185 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001186 Info.FirstArg = TemplateArgument(ParamIn);
1187 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001188
Douglas Gregorfb322d82011-01-14 05:11:40 +00001189 // If the parameter is an already-substituted template parameter
1190 // pack, do nothing: we don't know which of its arguments to look
1191 // at, so we have to wait until all of the parameter packs in this
1192 // expansion have arguments.
1193 if (isa<SubstTemplateTypeParmPackType>(Param))
1194 return Sema::TDK_Success;
1195
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001196 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001197 CanQualType CanParam = S.Context.getCanonicalType(Param);
1198 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001199 if (!(TDF & TDF_IgnoreQualifiers)) {
1200 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001201 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001202 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001203 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001204 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001205 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001206 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001207
1208 // If the parameter type is not dependent, there is nothing to deduce.
1209 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001210 if (!(TDF & TDF_SkipNonDependent)) {
1211 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1212 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1213 Param != Arg;
1214 if (NonDeduced) {
1215 return Sema::TDK_NonDeducedMismatch;
1216 }
1217 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001218 return Sema::TDK_Success;
1219 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001220 } else if (!Param->isDependentType()) {
1221 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1222 ArgUnqualType = CanArg.getUnqualifiedType();
1223 bool Success = (TDF & TDF_InOverloadResolution)?
1224 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1225 ArgUnqualType) :
1226 ParamUnqualType == ArgUnqualType;
1227 if (Success)
1228 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001229 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001230
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001231 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001232 // Non-canonical types cannot appear here.
1233#define NON_CANONICAL_TYPE(Class, Base) \
1234 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1235#define TYPE(Class, Base)
1236#include "clang/AST/TypeNodes.def"
1237
1238 case Type::TemplateTypeParm:
1239 case Type::SubstTemplateTypeParmPack:
1240 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001241
1242 // These types cannot be dependent, so simply check whether the types are
1243 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001244 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001245 case Type::VariableArray:
1246 case Type::Vector:
1247 case Type::FunctionNoProto:
1248 case Type::Record:
1249 case Type::Enum:
1250 case Type::ObjCObject:
1251 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001252 case Type::ObjCObjectPointer: {
1253 if (TDF & TDF_SkipNonDependent)
1254 return Sema::TDK_Success;
1255
1256 if (TDF & TDF_IgnoreQualifiers) {
1257 Param = Param.getUnqualifiedType();
1258 Arg = Arg.getUnqualifiedType();
1259 }
1260
1261 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1262 }
1263
Douglas Gregor39c02722011-06-15 16:02:29 +00001264 // _Complex T [placeholder extension]
1265 case Type::Complex:
1266 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001267 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001268 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001269 ComplexArg->getElementType(),
1270 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001271
1272 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001273
1274 // _Atomic T [extension]
1275 case Type::Atomic:
1276 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001277 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001278 cast<AtomicType>(Param)->getValueType(),
1279 AtomicArg->getValueType(),
1280 Info, Deduced, TDF);
1281
1282 return Sema::TDK_NonDeducedMismatch;
1283
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001284 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001285 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001286 QualType PointeeType;
1287 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1288 PointeeType = PointerArg->getPointeeType();
1289 } else if (const ObjCObjectPointerType *PointerArg
1290 = Arg->getAs<ObjCObjectPointerType>()) {
1291 PointeeType = PointerArg->getPointeeType();
1292 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001293 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregorfc516c92009-06-26 23:27:24 +00001296 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001297 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1298 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001299 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001300 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001303 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001304 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001305 const LValueReferenceType *ReferenceArg =
1306 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001307 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001308 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001310 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001311 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001312 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001313 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001314
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001315 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001316 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001317 const RValueReferenceType *ReferenceArg =
1318 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001319 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001320 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001322 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1323 cast<RValueReferenceType>(Param)->getPointeeType(),
1324 ReferenceArg->getPointeeType(),
1325 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001328 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001329 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001330 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001331 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001332 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001333 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001334
John McCallf7332682010-08-19 00:20:19 +00001335 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1337 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1338 IncompleteArrayArg->getElementType(),
1339 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001340 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001341
1342 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001343 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001344 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001345 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001346 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001347 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001348
1349 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001350 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001351 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001352 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001353
John McCallf7332682010-08-19 00:20:19 +00001354 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001355 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1356 ConstantArrayParm->getElementType(),
1357 ConstantArrayArg->getElementType(),
1358 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001359 }
1360
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001361 // type [i]
1362 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001363 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001364 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001365 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001366
John McCallf7332682010-08-19 00:20:19 +00001367 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1368
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001369 // Check the element type of the arrays
1370 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001371 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001372 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001373 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1374 DependentArrayParm->getElementType(),
1375 ArrayArg->getElementType(),
1376 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001377 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001379 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001380 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001381 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1382 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001383 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001384
1385 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001386 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001387 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001388 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001390 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1391 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001393 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001394 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001395 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001396 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001397 if (const DependentSizedArrayType *DependentArrayArg
1398 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001399 if (DependentArrayArg->getSizeExpr())
1400 return DeduceNonTypeTemplateArgument(S, NTTP,
1401 DependentArrayArg->getSizeExpr(),
1402 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001403
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001404 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001405 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
1408 // type(*)(T)
1409 // T(*)()
1410 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001411 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001412 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001413 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001414 dyn_cast<FunctionProtoType>(Arg);
1415 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001416 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001417
1418 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001419 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001420
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001422 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001424 != FunctionProtoArg->getRefQualifier() ||
1425 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001426 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001427
Anders Carlsson2128ec72009-06-08 15:19:08 +00001428 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001429 if (Sema::TemplateDeductionResult Result =
1430 DeduceTemplateArgumentsByTypeMatch(
1431 S, TemplateParams, FunctionProtoParam->getReturnType(),
1432 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001433 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001434
Alp Toker9cacbab2014-01-20 20:26:09 +00001435 return DeduceTemplateArguments(
1436 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1437 FunctionProtoParam->getNumParams(),
1438 FunctionProtoArg->param_type_begin(),
1439 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
John McCalle78aac42010-03-10 03:28:59 +00001442 case Type::InjectedClassName: {
1443 // Treat a template's injected-class-name as if the template
1444 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001445 Param = cast<InjectedClassNameType>(Param)
1446 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001447 assert(isa<TemplateSpecializationType>(Param) &&
1448 "injected class name is not a template specialization type");
1449 // fall through
1450 }
1451
Douglas Gregor705c9002009-06-26 20:57:09 +00001452 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001453 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001454 // TT<T>
1455 // TT<i>
1456 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001457 case Type::TemplateSpecialization: {
1458 const TemplateSpecializationType *SpecParam
1459 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregore81f3e72009-07-07 23:09:34 +00001461 // Try to deduce template arguments from the template-id.
1462 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001463 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001464 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregor42909752009-09-30 22:13:51 +00001466 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001467 // C++ [temp.deduct.call]p3b3:
1468 // If P is a class, and P has the form template-id, then A can be a
1469 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001470 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001471 // class pointed to by the deduced A.
1472 //
1473 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001474 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001475 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001476 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1477 // We cannot inspect base classes as part of deduction when the type
1478 // is incomplete, so either instantiate any templates necessary to
1479 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001480 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001481 return Result;
1482
Douglas Gregore81f3e72009-07-07 23:09:34 +00001483 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001484 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001485 // ToVisit is our stack of records that we still need to visit.
1486 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001488 ToVisit.push_back(RecordT);
1489 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001490 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1491 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001492 while (!ToVisit.empty()) {
1493 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001494 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001495
Douglas Gregore81f3e72009-07-07 23:09:34 +00001496 // If we have already seen this type, skip it.
1497 if (!Visited.insert(NextT))
1498 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregore81f3e72009-07-07 23:09:34 +00001500 // If this is a base class, try to perform template argument
1501 // deduction from it.
1502 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001503 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001504 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001505 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001506 QualType(NextT, 0), BaseInfo,
1507 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Douglas Gregore81f3e72009-07-07 23:09:34 +00001509 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001510 // note that we had some success. Otherwise, ignore any deductions
1511 // from this base class.
1512 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001513 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001514 DeducedOrig.clear();
1515 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001516 Info.Param = BaseInfo.Param;
1517 Info.FirstArg = BaseInfo.FirstArg;
1518 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001519 }
1520 else
1521 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001522 }
Mike Stump11289f42009-09-09 15:08:12 +00001523
Douglas Gregore81f3e72009-07-07 23:09:34 +00001524 // Visit base classes
1525 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001526 for (const auto &Base : Next->bases()) {
1527 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001528 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001529 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001530 }
1531 }
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregore81f3e72009-07-07 23:09:34 +00001533 if (Successful)
1534 return Sema::TDK_Success;
1535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregore81f3e72009-07-07 23:09:34 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregore81f3e72009-07-07 23:09:34 +00001539 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001540 }
1541
Douglas Gregor637d9982009-06-10 23:47:09 +00001542 // T type::*
1543 // T T::*
1544 // T (type::*)()
1545 // type (T::*)()
1546 // type (type::*)(T)
1547 // type (T::*)(T)
1548 // T (type::*)(T)
1549 // T (T::*)()
1550 // T (T::*)(T)
1551 case Type::MemberPointer: {
1552 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1553 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1554 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001555 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001556
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001557 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001558 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1559 MemPtrParam->getPointeeType(),
1560 MemPtrArg->getPointeeType(),
1561 Info, Deduced,
1562 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001563 return Result;
1564
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001565 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1566 QualType(MemPtrParam->getClass(), 0),
1567 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001568 Info, Deduced,
1569 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001570 }
1571
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001572 // (clang extension)
1573 //
Mike Stump11289f42009-09-09 15:08:12 +00001574 // type(^)(T)
1575 // T(^)()
1576 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001577 case Type::BlockPointer: {
1578 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1579 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001580
Anders Carlssona767eee2009-06-12 16:23:10 +00001581 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001582 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001583
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001584 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1585 BlockPtrParam->getPointeeType(),
1586 BlockPtrArg->getPointeeType(),
1587 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001588 }
1589
Douglas Gregor39c02722011-06-15 16:02:29 +00001590 // (clang extension)
1591 //
1592 // T __attribute__(((ext_vector_type(<integral constant>))))
1593 case Type::ExtVector: {
1594 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1595 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1596 // Make sure that the vectors have the same number of elements.
1597 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1598 return Sema::TDK_NonDeducedMismatch;
1599
1600 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001601 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1602 VectorParam->getElementType(),
1603 VectorArg->getElementType(),
1604 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001605 }
1606
1607 if (const DependentSizedExtVectorType *VectorArg
1608 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1609 // We can't check the number of elements, since the argument has a
1610 // dependent number of elements. This can only occur during partial
1611 // ordering.
1612
1613 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001614 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1615 VectorParam->getElementType(),
1616 VectorArg->getElementType(),
1617 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001618 }
1619
1620 return Sema::TDK_NonDeducedMismatch;
1621 }
1622
1623 // (clang extension)
1624 //
1625 // T __attribute__(((ext_vector_type(N))))
1626 case Type::DependentSizedExtVector: {
1627 const DependentSizedExtVectorType *VectorParam
1628 = cast<DependentSizedExtVectorType>(Param);
1629
1630 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1631 // Perform deduction on the element types.
1632 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001633 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1634 VectorParam->getElementType(),
1635 VectorArg->getElementType(),
1636 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001637 return Result;
1638
1639 // Perform deduction on the vector size, if we can.
1640 NonTypeTemplateParmDecl *NTTP
1641 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1642 if (!NTTP)
1643 return Sema::TDK_Success;
1644
1645 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1646 ArgSize = VectorArg->getNumElements();
1647 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1648 false, Info, Deduced);
1649 }
1650
1651 if (const DependentSizedExtVectorType *VectorArg
1652 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1653 // Perform deduction on the element types.
1654 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001655 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1656 VectorParam->getElementType(),
1657 VectorArg->getElementType(),
1658 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001659 return Result;
1660
1661 // Perform deduction on the vector size, if we can.
1662 NonTypeTemplateParmDecl *NTTP
1663 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1664 if (!NTTP)
1665 return Sema::TDK_Success;
1666
1667 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1668 Info, Deduced);
1669 }
1670
1671 return Sema::TDK_NonDeducedMismatch;
1672 }
1673
Douglas Gregor637d9982009-06-10 23:47:09 +00001674 case Type::TypeOfExpr:
1675 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001676 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001677 case Type::UnresolvedUsing:
1678 case Type::Decltype:
1679 case Type::UnaryTransform:
1680 case Type::Auto:
1681 case Type::DependentTemplateSpecialization:
1682 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001683 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001684 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001685 }
1686
David Blaikiee4d798f2012-01-20 21:50:17 +00001687 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001688}
1689
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001690static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001691DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001692 TemplateParameterList *TemplateParams,
1693 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001694 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001695 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001696 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001697 // If the template argument is a pack expansion, perform template argument
1698 // deduction against the pattern of that expansion. This only occurs during
1699 // partial ordering.
1700 if (Arg.isPackExpansion())
1701 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001703 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001704 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001705 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001706
1707 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001708 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001709 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1710 Param.getAsType(),
1711 Arg.getAsType(),
1712 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001713 Info.FirstArg = Param;
1714 Info.SecondArg = Arg;
1715 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001716
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001717 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001718 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001720 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001721 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001722 Info.FirstArg = Param;
1723 Info.SecondArg = Arg;
1724 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001725
1726 case TemplateArgument::TemplateExpansion:
1727 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001729 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001730 if (Arg.getKind() == TemplateArgument::Declaration &&
Eli Friedmanb826a002012-09-26 02:36:12 +00001731 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()) &&
1732 Param.isDeclForReferenceParam() == Arg.isDeclForReferenceParam())
1733 return Sema::TDK_Success;
1734
1735 Info.FirstArg = Param;
1736 Info.SecondArg = Arg;
1737 return Sema::TDK_NonDeducedMismatch;
1738
1739 case TemplateArgument::NullPtr:
1740 if (Arg.getKind() == TemplateArgument::NullPtr &&
1741 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001742 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001744 Info.FirstArg = Param;
1745 Info.SecondArg = Arg;
1746 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001748 case TemplateArgument::Integral:
1749 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001750 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001751 return Sema::TDK_Success;
1752
1753 Info.FirstArg = Param;
1754 Info.SecondArg = Arg;
1755 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001756 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001757
1758 if (Arg.getKind() == TemplateArgument::Expression) {
1759 Info.FirstArg = Param;
1760 Info.SecondArg = Arg;
1761 return Sema::TDK_NonDeducedMismatch;
1762 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001763
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001764 Info.FirstArg = Param;
1765 Info.SecondArg = Arg;
1766 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001767
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001768 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001769 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001770 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1771 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001772 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001773 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001774 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001775 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001776 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001777 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001778 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001779 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001780 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001781 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001782 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001784 Info.FirstArg = Param;
1785 Info.SecondArg = Arg;
1786 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001789 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001790 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001791 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001792 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001793 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795
David Blaikiee4d798f2012-01-20 21:50:17 +00001796 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001797}
1798
Douglas Gregor7baabef2010-12-22 18:17:10 +00001799/// \brief Determine whether there is a template argument to be used for
1800/// deduction.
1801///
1802/// This routine "expands" argument packs in-place, overriding its input
1803/// parameters so that \c Args[ArgIdx] will be the available template argument.
1804///
1805/// \returns true if there is another template argument (which will be at
1806/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001808 unsigned &ArgIdx,
1809 unsigned &NumArgs) {
1810 if (ArgIdx == NumArgs)
1811 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Douglas Gregor7baabef2010-12-22 18:17:10 +00001813 const TemplateArgument &Arg = Args[ArgIdx];
1814 if (Arg.getKind() != TemplateArgument::Pack)
1815 return true;
1816
1817 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1818 Args = Arg.pack_begin();
1819 NumArgs = Arg.pack_size();
1820 ArgIdx = 0;
1821 return ArgIdx < NumArgs;
1822}
1823
Douglas Gregord0ad2942010-12-23 01:24:45 +00001824/// \brief Determine whether the given set of template arguments has a pack
1825/// expansion that is not the last template argument.
1826static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1827 unsigned NumArgs) {
1828 unsigned ArgIdx = 0;
1829 while (ArgIdx < NumArgs) {
1830 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831
Douglas Gregord0ad2942010-12-23 01:24:45 +00001832 // Unwrap argument packs.
1833 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1834 Args = Arg.pack_begin();
1835 NumArgs = Arg.pack_size();
1836 ArgIdx = 0;
1837 continue;
1838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839
Douglas Gregord0ad2942010-12-23 01:24:45 +00001840 ++ArgIdx;
1841 if (ArgIdx == NumArgs)
1842 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001843
Douglas Gregord0ad2942010-12-23 01:24:45 +00001844 if (Arg.isPackExpansion())
1845 return true;
1846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001847
Douglas Gregord0ad2942010-12-23 01:24:45 +00001848 return false;
1849}
1850
Douglas Gregor7baabef2010-12-22 18:17:10 +00001851static Sema::TemplateDeductionResult
1852DeduceTemplateArguments(Sema &S,
1853 TemplateParameterList *TemplateParams,
1854 const TemplateArgument *Params, unsigned NumParams,
1855 const TemplateArgument *Args, unsigned NumArgs,
1856 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001857 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001858 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859 // If the template argument list of P contains a pack expansion that is not
1860 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001861 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001862 if (hasPackExpansionBeforeEnd(Params, NumParams))
1863 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001865 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866 // If P has a form that contains <T> or <i>, then each argument Pi of the
1867 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001868 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871 ++ParamIdx) {
1872 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001873 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
Douglas Gregor7baabef2010-12-22 18:17:10 +00001875 // Check whether we have enough arguments.
1876 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001877 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001879 if (Args[ArgIdx].isPackExpansion()) {
1880 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1881 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001882 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001884
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001885 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001886 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001887 = DeduceTemplateArguments(S, TemplateParams,
1888 Params[ParamIdx], Args[ArgIdx],
1889 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890 return Result;
1891
Douglas Gregor7baabef2010-12-22 18:17:10 +00001892 // Move to the next argument.
1893 ++ArgIdx;
1894 continue;
1895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001897 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001899 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900 // If Pi is a pack expansion, then the pattern of Pi is compared with
1901 // each remaining argument in the template argument list of A. Each
1902 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001903 // template parameter packs expanded by Pi.
1904 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001906 // FIXME: If there are no remaining arguments, we can bail out early
1907 // and set any deduced parameter packs to an empty argument pack.
1908 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909
Richard Smith0a80d572014-05-29 01:12:14 +00001910 // Prepare to deduce the packs within the pattern.
1911 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001912
1913 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001915 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001917 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001918 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001922 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1923 Info, Deduced))
1924 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Richard Smith0a80d572014-05-29 01:12:14 +00001926 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001929 // Build argument packs for each of the parameter packs expanded by this
1930 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001931 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934
Douglas Gregor7baabef2010-12-22 18:17:10 +00001935 return Sema::TDK_Success;
1936}
1937
Mike Stump11289f42009-09-09 15:08:12 +00001938static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001939DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001940 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001941 const TemplateArgumentList &ParamList,
1942 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001943 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001944 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001946 ParamList.data(), ParamList.size(),
1947 ArgList.data(), ArgList.size(),
1948 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001949}
1950
Douglas Gregor705c9002009-06-26 20:57:09 +00001951/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001952static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001953 const TemplateArgument &X,
1954 const TemplateArgument &Y) {
1955 if (X.getKind() != Y.getKind())
1956 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001957
Douglas Gregor705c9002009-06-26 20:57:09 +00001958 switch (X.getKind()) {
1959 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001960 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregor705c9002009-06-26 20:57:09 +00001962 case TemplateArgument::Type:
1963 return Context.getCanonicalType(X.getAsType()) ==
1964 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001965
Douglas Gregor705c9002009-06-26 20:57:09 +00001966 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00001967 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
1968 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam();
1969
1970 case TemplateArgument::NullPtr:
1971 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001972
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001973 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001974 case TemplateArgument::TemplateExpansion:
1975 return Context.getCanonicalTemplateName(
1976 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1977 Context.getCanonicalTemplateName(
1978 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979
Douglas Gregor705c9002009-06-26 20:57:09 +00001980 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001981 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001983 case TemplateArgument::Expression: {
1984 llvm::FoldingSetNodeID XID, YID;
1985 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001987 return XID == YID;
1988 }
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregor705c9002009-06-26 20:57:09 +00001990 case TemplateArgument::Pack:
1991 if (X.pack_size() != Y.pack_size())
1992 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001993
1994 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1995 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001996 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001997 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001998 if (!isSameTemplateArg(Context, *XP, *YP))
1999 return false;
2000
2001 return true;
2002 }
2003
David Blaikiee4d798f2012-01-20 21:50:17 +00002004 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002005}
2006
Douglas Gregorca4686d2011-01-04 23:35:54 +00002007/// \brief Allocate a TemplateArgumentLoc where all locations have
2008/// been initialized to the given location.
2009///
2010/// \param S The semantic analysis object.
2011///
James Dennett634962f2012-06-14 21:40:34 +00002012/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002013/// location information for.
2014///
2015/// \param NTTPType For a declaration template argument, the type of
2016/// the non-type template parameter that corresponds to this template
2017/// argument.
2018///
2019/// \param Loc The source location to use for the resulting template
2020/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00002022getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002024 QualType NTTPType,
2025 SourceLocation Loc) {
2026 switch (Arg.getKind()) {
2027 case TemplateArgument::Null:
2028 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029
Douglas Gregorca4686d2011-01-04 23:35:54 +00002030 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002032 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033
Douglas Gregorca4686d2011-01-04 23:35:54 +00002034 case TemplateArgument::Declaration: {
2035 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002036 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002037 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002038 return TemplateArgumentLoc(TemplateArgument(E), E);
2039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
Eli Friedmanb826a002012-09-26 02:36:12 +00002041 case TemplateArgument::NullPtr: {
2042 Expr *E
2043 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002044 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002045 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2046 E);
2047 }
2048
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049 case TemplateArgument::Integral: {
2050 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002051 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052 return TemplateArgumentLoc(TemplateArgument(E), E);
2053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Douglas Gregor9d802122011-03-02 17:09:35 +00002055 case TemplateArgument::Template:
2056 case TemplateArgument::TemplateExpansion: {
2057 NestedNameSpecifierLocBuilder Builder;
2058 TemplateName Template = Arg.getAsTemplate();
2059 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2060 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002061 else if (QualifiedTemplateName *QTN =
2062 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002063 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2064
2065 if (Arg.getKind() == TemplateArgument::Template)
2066 return TemplateArgumentLoc(Arg,
2067 Builder.getWithLocInContext(S.Context),
2068 Loc);
2069
2070
2071 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2072 Loc, Loc);
2073 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002074
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075 case TemplateArgument::Expression:
2076 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Douglas Gregorca4686d2011-01-04 23:35:54 +00002078 case TemplateArgument::Pack:
2079 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
David Blaikiee4d798f2012-01-20 21:50:17 +00002082 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002083}
2084
2085
2086/// \brief Convert the given deduced template argument and add it to the set of
2087/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002088static bool
2089ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2090 DeducedTemplateArgument Arg,
2091 NamedDecl *Template,
2092 QualType NTTPType,
2093 unsigned ArgumentPackIndex,
2094 TemplateDeductionInfo &Info,
2095 bool InFunctionTemplate,
2096 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002097 if (Arg.getKind() == TemplateArgument::Pack) {
2098 // This is a template argument pack, so check each of its arguments against
2099 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002100 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002101 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002102 // When converting the deduced template argument, append it to the
2103 // general output list. We need to do this so that the template argument
2104 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002105 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002106 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002108 NTTPType, PackedArgsBuilder.size(),
2109 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002110 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002111
Douglas Gregor51bc5712011-01-05 20:52:18 +00002112 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002113 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115
Douglas Gregorca4686d2011-01-04 23:35:54 +00002116 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002118 PackedArgsBuilder.data(),
2119 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 return false;
2121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
Douglas Gregorca4686d2011-01-04 23:35:54 +00002123 // Convert the deduced template argument into a template
2124 // argument that we can check, almost as if the user had written
2125 // the template argument explicitly.
2126 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2127 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Douglas Gregorca4686d2011-01-04 23:35:54 +00002129 // Check the template argument, converting it as necessary.
2130 return S.CheckTemplateArgument(Param, ArgLoc,
2131 Template,
2132 Template->getLocation(),
2133 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002134 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002135 Output,
2136 InFunctionTemplate
2137 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002139 : Sema::CTAK_Deduced)
2140 : Sema::CTAK_Specified);
2141}
2142
Douglas Gregor684268d2010-04-29 06:21:43 +00002143/// Complete template argument deduction for a class template partial
2144/// specialization.
2145static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002147 ClassTemplatePartialSpecializationDecl *Partial,
2148 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002149 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002150 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002151 // Unevaluated SFINAE context.
2152 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002153 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregor684268d2010-04-29 06:21:43 +00002155 Sema::ContextRAII SavedContext(S, Partial);
2156
2157 // C++ [temp.deduct.type]p2:
2158 // [...] or if any template argument remains neither deduced nor
2159 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002160 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002161 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2162 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002163 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002164 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002165 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002166 return Sema::TDK_Incomplete;
2167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregorca4686d2011-01-04 23:35:54 +00002169 // We have deduced this argument, so it still needs to be
2170 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171
Douglas Gregorca4686d2011-01-04 23:35:54 +00002172 // First, for a non-type template parameter type that is
2173 // initialized by a declaration, we need the type of the
2174 // corresponding non-type template parameter.
2175 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002177 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002178 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002179 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002181 Builder.data(), Builder.size());
2182 NTTPType = S.SubstType(NTTPType,
2183 MultiLevelTemplateArgumentList(TemplateArgs),
2184 NTTP->getLocation(),
2185 NTTP->getDeclName());
2186 if (NTTPType.isNull()) {
2187 Info.Param = makeTemplateParameter(Param);
2188 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2190 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002191 Builder.size()));
2192 return Sema::TDK_SubstitutionFailure;
2193 }
2194 }
2195 }
2196
Douglas Gregorca4686d2011-01-04 23:35:54 +00002197 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002198 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002199 Builder)) {
2200 Info.Param = makeTemplateParameter(Param);
2201 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2203 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002204 return Sema::TDK_SubstitutionFailure;
2205 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207
Douglas Gregor684268d2010-04-29 06:21:43 +00002208 // Form the template argument list from the deduced template arguments.
2209 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002211 Builder.size());
2212
Douglas Gregor684268d2010-04-29 06:21:43 +00002213 Info.reset(DeducedArgumentList);
2214
2215 // Substitute the deduced template arguments into the template
2216 // arguments of the class template partial specialization, and
2217 // verify that the instantiated template arguments are both valid
2218 // and are equivalent to the template arguments originally provided
2219 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002220 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002221 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002222 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002223 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002224 const TemplateArgumentLoc *PartialTemplateArgs
2225 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002226
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002227 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2228 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002229
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002230 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002231 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2232 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2233 if (ParamIdx >= Partial->getTemplateParameters()->size())
2234 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2235
2236 Decl *Param
2237 = const_cast<NamedDecl *>(
2238 Partial->getTemplateParameters()->getParam(ParamIdx));
2239 Info.Param = makeTemplateParameter(Param);
2240 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2241 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002242 }
2243
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002244 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002245 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002246 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002247 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248
Douglas Gregorca4686d2011-01-04 23:35:54 +00002249 TemplateParameterList *TemplateParams
2250 = ClassTemplate->getTemplateParameters();
2251 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002252 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002253 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002254 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002255 Info.FirstArg = TemplateArgs[I];
2256 Info.SecondArg = InstArg;
2257 return Sema::TDK_NonDeducedMismatch;
2258 }
2259 }
2260
2261 if (Trap.hasErrorOccurred())
2262 return Sema::TDK_SubstitutionFailure;
2263
2264 return Sema::TDK_Success;
2265}
2266
Douglas Gregor170bc422009-06-12 22:31:52 +00002267/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002268/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002269/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002270Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002271Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002272 const TemplateArgumentList &TemplateArgs,
2273 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002274 if (Partial->isInvalidDecl())
2275 return TDK_Invalid;
2276
Douglas Gregor170bc422009-06-12 22:31:52 +00002277 // C++ [temp.class.spec.match]p2:
2278 // A partial specialization matches a given actual template
2279 // argument list if the template arguments of the partial
2280 // specialization can be deduced from the actual template argument
2281 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002282
2283 // Unevaluated SFINAE context.
2284 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002285 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002286
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002287 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002288 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002289 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002290 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002291 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002292 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002293 TemplateArgs, Info, Deduced))
2294 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002295
Richard Smith80934652012-07-16 01:09:10 +00002296 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002297 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2298 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002299 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002300 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002301
Douglas Gregore1416332009-06-14 08:02:22 +00002302 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002303 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
2305 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002306 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002307}
Douglas Gregor91772d12009-06-13 00:26:55 +00002308
Larisse Voufo39a1e502013-08-06 01:03:05 +00002309/// Complete template argument deduction for a variable template partial
2310/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002311/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2312/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2313/// VarTemplate(Partial)SpecializationDecl with a new data
2314/// structure Template(Partial)SpecializationDecl, and
2315/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002316static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2317 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2318 const TemplateArgumentList &TemplateArgs,
2319 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2320 TemplateDeductionInfo &Info) {
2321 // Unevaluated SFINAE context.
2322 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2323 Sema::SFINAETrap Trap(S);
2324
2325 // C++ [temp.deduct.type]p2:
2326 // [...] or if any template argument remains neither deduced nor
2327 // explicitly specified, template argument deduction fails.
2328 SmallVector<TemplateArgument, 4> Builder;
2329 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2330 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2331 NamedDecl *Param = PartialParams->getParam(I);
2332 if (Deduced[I].isNull()) {
2333 Info.Param = makeTemplateParameter(Param);
2334 return Sema::TDK_Incomplete;
2335 }
2336
2337 // We have deduced this argument, so it still needs to be
2338 // checked and converted.
2339
2340 // First, for a non-type template parameter type that is
2341 // initialized by a declaration, we need the type of the
2342 // corresponding non-type template parameter.
2343 QualType NTTPType;
2344 if (NonTypeTemplateParmDecl *NTTP =
2345 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2346 NTTPType = NTTP->getType();
2347 if (NTTPType->isDependentType()) {
2348 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2349 Builder.data(), Builder.size());
2350 NTTPType =
2351 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2352 NTTP->getLocation(), NTTP->getDeclName());
2353 if (NTTPType.isNull()) {
2354 Info.Param = makeTemplateParameter(Param);
2355 // FIXME: These template arguments are temporary. Free them!
2356 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2357 Builder.size()));
2358 return Sema::TDK_SubstitutionFailure;
2359 }
2360 }
2361 }
2362
2363 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2364 0, Info, false, Builder)) {
2365 Info.Param = makeTemplateParameter(Param);
2366 // FIXME: These template arguments are temporary. Free them!
2367 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2368 Builder.size()));
2369 return Sema::TDK_SubstitutionFailure;
2370 }
2371 }
2372
2373 // Form the template argument list from the deduced template arguments.
2374 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2375 S.Context, Builder.data(), Builder.size());
2376
2377 Info.reset(DeducedArgumentList);
2378
2379 // Substitute the deduced template arguments into the template
2380 // arguments of the class template partial specialization, and
2381 // verify that the instantiated template arguments are both valid
2382 // and are equivalent to the template arguments originally provided
2383 // to the class template.
2384 LocalInstantiationScope InstScope(S);
2385 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002386 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2387 = Partial->getTemplateArgsAsWritten();
2388 const TemplateArgumentLoc *PartialTemplateArgs
2389 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002390
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002391 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2392 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002393
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002394 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002395 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2396 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2397 if (ParamIdx >= Partial->getTemplateParameters()->size())
2398 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2399
2400 Decl *Param = const_cast<NamedDecl *>(
2401 Partial->getTemplateParameters()->getParam(ParamIdx));
2402 Info.Param = makeTemplateParameter(Param);
2403 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2404 return Sema::TDK_SubstitutionFailure;
2405 }
2406 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2407 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2408 false, ConvertedInstArgs))
2409 return Sema::TDK_SubstitutionFailure;
2410
2411 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2412 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2413 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2414 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2415 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2416 Info.FirstArg = TemplateArgs[I];
2417 Info.SecondArg = InstArg;
2418 return Sema::TDK_NonDeducedMismatch;
2419 }
2420 }
2421
2422 if (Trap.hasErrorOccurred())
2423 return Sema::TDK_SubstitutionFailure;
2424
2425 return Sema::TDK_Success;
2426}
2427
2428/// \brief Perform template argument deduction to determine whether
2429/// the given template arguments match the given variable template
2430/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002431/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2432/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2433/// VarTemplate(Partial)SpecializationDecl with a new data
2434/// structure Template(Partial)SpecializationDecl, and
2435/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002436Sema::TemplateDeductionResult
2437Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2438 const TemplateArgumentList &TemplateArgs,
2439 TemplateDeductionInfo &Info) {
2440 if (Partial->isInvalidDecl())
2441 return TDK_Invalid;
2442
2443 // C++ [temp.class.spec.match]p2:
2444 // A partial specialization matches a given actual template
2445 // argument list if the template arguments of the partial
2446 // specialization can be deduced from the actual template argument
2447 // list (14.8.2).
2448
2449 // Unevaluated SFINAE context.
2450 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2451 SFINAETrap Trap(*this);
2452
2453 SmallVector<DeducedTemplateArgument, 4> Deduced;
2454 Deduced.resize(Partial->getTemplateParameters()->size());
2455 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2456 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2457 TemplateArgs, Info, Deduced))
2458 return Result;
2459
2460 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002461 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2462 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002463 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002464 return TDK_InstantiationDepth;
2465
2466 if (Trap.hasErrorOccurred())
2467 return Sema::TDK_SubstitutionFailure;
2468
2469 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2470 Deduced, Info);
2471}
2472
Douglas Gregorfc516c92009-06-26 23:27:24 +00002473/// \brief Determine whether the given type T is a simple-template-id type.
2474static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002475 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002476 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002477 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002478
Douglas Gregorfc516c92009-06-26 23:27:24 +00002479 return false;
2480}
Douglas Gregor9b146582009-07-08 20:55:45 +00002481
2482/// \brief Substitute the explicitly-provided template arguments into the
2483/// given function template according to C++ [temp.arg.explicit].
2484///
2485/// \param FunctionTemplate the function template into which the explicit
2486/// template arguments will be substituted.
2487///
James Dennett634962f2012-06-14 21:40:34 +00002488/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002489/// arguments.
2490///
Mike Stump11289f42009-09-09 15:08:12 +00002491/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002492/// with the converted and checked explicit template arguments.
2493///
Mike Stump11289f42009-09-09 15:08:12 +00002494/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002495/// parameters.
2496///
2497/// \param FunctionType if non-NULL, the result type of the function template
2498/// will also be instantiated and the pointed-to value will be updated with
2499/// the instantiated function type.
2500///
2501/// \param Info if substitution fails for any reason, this object will be
2502/// populated with more information about the failure.
2503///
2504/// \returns TDK_Success if substitution was successful, or some failure
2505/// condition.
2506Sema::TemplateDeductionResult
2507Sema::SubstituteExplicitTemplateArguments(
2508 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002509 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002510 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2511 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002512 QualType *FunctionType,
2513 TemplateDeductionInfo &Info) {
2514 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2515 TemplateParameterList *TemplateParams
2516 = FunctionTemplate->getTemplateParameters();
2517
John McCall6b51f282009-11-23 01:53:49 +00002518 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002519 // No arguments to substitute; just copy over the parameter types and
2520 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002521 for (auto P : Function->params())
2522 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor9b146582009-07-08 20:55:45 +00002524 if (FunctionType)
2525 *FunctionType = Function->getType();
2526 return TDK_Success;
2527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
Eli Friedman77dcc722012-02-08 03:07:05 +00002529 // Unevaluated SFINAE context.
2530 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002531 SFINAETrap Trap(*this);
2532
Douglas Gregor9b146582009-07-08 20:55:45 +00002533 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002534 // Template arguments that are present shall be specified in the
2535 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002536 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002537 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002538 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002539
2540 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002541 // explicitly-specified template arguments against this function template,
2542 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002543 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002544 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2545 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002546 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2547 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002548 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002549 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor9b146582009-07-08 20:55:45 +00002551 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002552 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002553 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002554 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002555 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002556 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002557 if (Index >= TemplateParams->size())
2558 Index = TemplateParams->size() - 1;
2559 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002560 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregor9b146582009-07-08 20:55:45 +00002563 // Form the template argument list from the explicitly-specified
2564 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002565 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002566 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002567 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568
John McCall036855a2010-10-12 19:40:14 +00002569 // Template argument deduction and the final substitution should be
2570 // done in the context of the templated declaration. Explicit
2571 // argument substitution, on the other hand, needs to happen in the
2572 // calling context.
2573 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002576 // note that the template argument pack is partially substituted and record
2577 // the explicit template arguments. They'll be used as part of deduction
2578 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002579 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2580 const TemplateArgument &Arg = Builder[I];
2581 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002582 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002583 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002584 Arg.pack_begin(),
2585 Arg.pack_size());
2586 break;
2587 }
2588 }
2589
Richard Smith5e580292012-02-10 09:58:53 +00002590 const FunctionProtoType *Proto
2591 = Function->getType()->getAs<FunctionProtoType>();
2592 assert(Proto && "Function template does not have a prototype?");
2593
Douglas Gregor9b146582009-07-08 20:55:45 +00002594 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002595 // explicitly-specified template arguments. If the function has a trailing
2596 // return type, substitute it after the arguments to ensure we substitute
2597 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002598 if (Proto->hasTrailingReturn()) {
2599 if (SubstParmTypes(Function->getLocation(),
2600 Function->param_begin(), Function->getNumParams(),
2601 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2602 ParamTypes))
2603 return TDK_SubstitutionFailure;
2604 }
2605
Richard Smith5e580292012-02-10 09:58:53 +00002606 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002607 QualType ResultType;
2608 {
2609 // C++11 [expr.prim.general]p3:
2610 // If a declaration declares a member function or member function
2611 // template of a class X, the expression this is a prvalue of type
2612 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2613 // and the end of the function-definition, member-declarator, or
2614 // declarator.
2615 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002616 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2618 ThisContext = Method->getParent();
2619 ThisTypeQuals = Method->getTypeQualifiers();
2620 }
2621
2622 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002623 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002624
2625 ResultType =
2626 SubstType(Proto->getReturnType(),
2627 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2628 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002629 if (ResultType.isNull() || Trap.hasErrorOccurred())
2630 return TDK_SubstitutionFailure;
2631 }
2632
Richard Smith5e580292012-02-10 09:58:53 +00002633 // Instantiate the types of each of the function parameters given the
2634 // explicitly-specified template arguments if we didn't do so earlier.
2635 if (!Proto->hasTrailingReturn() &&
2636 SubstParmTypes(Function->getLocation(),
2637 Function->param_begin(), Function->getNumParams(),
2638 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2639 ParamTypes))
2640 return TDK_SubstitutionFailure;
2641
Douglas Gregor9b146582009-07-08 20:55:45 +00002642 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002643 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002644 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002645 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002646 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002647 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2648 return TDK_SubstitutionFailure;
2649 }
Mike Stump11289f42009-09-09 15:08:12 +00002650
Douglas Gregor9b146582009-07-08 20:55:45 +00002651 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002652 // Trailing template arguments that can be deduced (14.8.2) may be
2653 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002654 // template arguments can be deduced, they may all be omitted; in this
2655 // case, the empty template argument list <> itself may also be omitted.
2656 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002657 // Take all of the explicitly-specified arguments and put them into
2658 // the set of deduced template arguments. Explicitly-specified
2659 // parameter packs, however, will be set to NULL since the deduction
2660 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002661 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002662 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2663 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2664 if (Arg.getKind() == TemplateArgument::Pack)
2665 Deduced.push_back(DeducedTemplateArgument());
2666 else
2667 Deduced.push_back(Arg);
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregor9b146582009-07-08 20:55:45 +00002670 return TDK_Success;
2671}
2672
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002673/// \brief Check whether the deduced argument type for a call to a function
2674/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2675static bool
2676CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2677 QualType DeducedA) {
2678 ASTContext &Context = S.Context;
2679
2680 QualType A = OriginalArg.OriginalArgType;
2681 QualType OriginalParamType = OriginalArg.OriginalParamType;
2682
2683 // Check for type equality (top-level cv-qualifiers are ignored).
2684 if (Context.hasSameUnqualifiedType(A, DeducedA))
2685 return false;
2686
2687 // Strip off references on the argument types; they aren't needed for
2688 // the following checks.
2689 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2690 DeducedA = DeducedARef->getPointeeType();
2691 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2692 A = ARef->getPointeeType();
2693
2694 // C++ [temp.deduct.call]p4:
2695 // [...] However, there are three cases that allow a difference:
2696 // - If the original P is a reference type, the deduced A (i.e., the
2697 // type referred to by the reference) can be more cv-qualified than
2698 // the transformed A.
2699 if (const ReferenceType *OriginalParamRef
2700 = OriginalParamType->getAs<ReferenceType>()) {
2701 // We don't want to keep the reference around any more.
2702 OriginalParamType = OriginalParamRef->getPointeeType();
2703
2704 Qualifiers AQuals = A.getQualifiers();
2705 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002706
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002707 // Under Objective-C++ ARC, the deduced type may have implicitly
2708 // been given strong or (when dealing with a const reference)
2709 // unsafe_unretained lifetime. If so, update the original
2710 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002711 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002712 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2713 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2714 (DeducedAQuals.hasConst() &&
2715 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2716 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002717 }
2718
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002719 if (AQuals == DeducedAQuals) {
2720 // Qualifiers match; there's nothing to do.
2721 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002722 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002723 } else {
2724 // Qualifiers are compatible, so have the argument type adopt the
2725 // deduced argument type's qualifiers as if we had performed the
2726 // qualification conversion.
2727 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2728 }
2729 }
2730
2731 // - The transformed A can be another pointer or pointer to member
2732 // type that can be converted to the deduced A via a qualification
2733 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002734 //
2735 // Also allow conversions which merely strip [[noreturn]] from function types
2736 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002737 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002738 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002739 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002740 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002741 (S.IsQualificationConversion(A, DeducedA, false,
2742 ObjCLifetimeConversion) ||
2743 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002744 return false;
2745
2746
2747 // - If P is a class and P has the form simple-template-id, then the
2748 // transformed A can be a derived class of the deduced A. [...]
2749 // [...] Likewise, if P is a pointer to a class of the form
2750 // simple-template-id, the transformed A can be a pointer to a
2751 // derived class pointed to by the deduced A.
2752 if (const PointerType *OriginalParamPtr
2753 = OriginalParamType->getAs<PointerType>()) {
2754 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2755 if (const PointerType *APtr = A->getAs<PointerType>()) {
2756 if (A->getPointeeType()->isRecordType()) {
2757 OriginalParamType = OriginalParamPtr->getPointeeType();
2758 DeducedA = DeducedAPtr->getPointeeType();
2759 A = APtr->getPointeeType();
2760 }
2761 }
2762 }
2763 }
2764
2765 if (Context.hasSameUnqualifiedType(A, DeducedA))
2766 return false;
2767
2768 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2769 S.IsDerivedFrom(A, DeducedA))
2770 return false;
2771
2772 return true;
2773}
2774
Mike Stump11289f42009-09-09 15:08:12 +00002775/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002776/// checking the deduced template arguments for completeness and forming
2777/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002778///
2779/// \param OriginalCallArgs If non-NULL, the original call arguments against
2780/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002781Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002782Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002783 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002784 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002785 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002786 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002787 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002788 TemplateParameterList *TemplateParams
2789 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002790
Eli Friedman77dcc722012-02-08 03:07:05 +00002791 // Unevaluated SFINAE context.
2792 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002793 SFINAETrap Trap(*this);
2794
Douglas Gregor9b146582009-07-08 20:55:45 +00002795 // Enter a new template instantiation context while we instantiate the
2796 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002797 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002798 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2799 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002800 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2801 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002802 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002803 return TDK_InstantiationDepth;
2804
John McCalle23b8712010-04-29 01:18:58 +00002805 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002806
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002807 // C++ [temp.deduct.type]p2:
2808 // [...] or if any template argument remains neither deduced nor
2809 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002810 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002811 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2812 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002814 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002815 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002816 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002818 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002819 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002820 // We may have had explicitly-specified template arguments for a
2821 // template parameter pack (that may or may not have been extended
2822 // via additional deduced arguments).
2823 if (Param->isParameterPack() && CurrentInstantiationScope) {
2824 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2825 Param) {
2826 // Forget the partially-substituted pack; its substitution is now
2827 // complete.
2828 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2829 }
2830 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002831 continue;
2832 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002833 // We have deduced this argument, so it still needs to be
2834 // checked and converted.
2835
2836 // First, for a non-type template parameter type that is
2837 // initialized by a declaration, we need the type of the
2838 // corresponding non-type template parameter.
2839 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840 if (NonTypeTemplateParmDecl *NTTP
2841 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002842 NTTPType = NTTP->getType();
2843 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002845 Builder.data(), Builder.size());
2846 NTTPType = SubstType(NTTPType,
2847 MultiLevelTemplateArgumentList(TemplateArgs),
2848 NTTP->getLocation(),
2849 NTTP->getDeclName());
2850 if (NTTPType.isNull()) {
2851 Info.Param = makeTemplateParameter(Param);
2852 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853 Info.reset(TemplateArgumentList::CreateCopy(Context,
2854 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002855 Builder.size()));
2856 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002857 }
2858 }
2859 }
2860
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002861 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002862 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002863 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002864 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002865 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2867 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002868 return TDK_SubstitutionFailure;
2869 }
2870
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002871 continue;
2872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002874 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002876 // be deduced to an empty sequence of template arguments.
2877 // FIXME: Where did the word "trailing" come from?
2878 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002879 // We may have had explicitly-specified template arguments for this
2880 // template parameter pack. If so, our empty deduction extends the
2881 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2882 const TemplateArgument *ExplicitArgs;
2883 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002884 if (CurrentInstantiationScope &&
2885 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002886 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002887 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002888 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889
Douglas Gregorcaddba92013-01-18 22:27:09 +00002890 // Forget the partially-substituted pack; it's substitution is now
2891 // complete.
2892 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2893 } else {
2894 Builder.push_back(TemplateArgument::getEmptyPack());
2895 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002896 continue;
2897 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002898
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002900 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002901 TemplateArgumentLoc DefArg
2902 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2903 FunctionTemplate->getLocation(),
2904 FunctionTemplate->getSourceRange().getEnd(),
2905 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002906 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002907
2908 // If there was no default argument, deduction is incomplete.
2909 if (DefArg.getArgument().isNull()) {
2910 Info.Param = makeTemplateParameter(
2911 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002912 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2913 Builder.size()));
2914 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002917 // Check whether we can actually use the default argument.
2918 if (CheckTemplateArgument(Param, DefArg,
2919 FunctionTemplate,
2920 FunctionTemplate->getLocation(),
2921 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002922 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002923 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002924 Info.Param = makeTemplateParameter(
2925 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002926 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002928 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002929 return TDK_SubstitutionFailure;
2930 }
2931
2932 // If we get here, we successfully used the default template argument.
2933 }
2934
2935 // Form the template argument list from the deduced template arguments.
2936 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002937 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002938 Info.reset(DeducedArgumentList);
2939
Mike Stump11289f42009-09-09 15:08:12 +00002940 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002941 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002942 DeclContext *Owner = FunctionTemplate->getDeclContext();
2943 if (FunctionTemplate->getFriendObjectKind())
2944 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002945 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002946 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002947 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002948 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002949 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002952 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953
Mike Stump11289f42009-09-09 15:08:12 +00002954 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002955 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002956 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2957 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002958 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002960 // There may have been an error that did not prevent us from constructing a
2961 // declaration. Mark the declaration invalid and return with a substitution
2962 // failure.
2963 if (Trap.hasErrorOccurred()) {
2964 Specialization->setInvalidDecl(true);
2965 return TDK_SubstitutionFailure;
2966 }
2967
Douglas Gregore65aacb2011-06-16 16:50:48 +00002968 if (OriginalCallArgs) {
2969 // C++ [temp.deduct.call]p4:
2970 // In general, the deduction process attempts to find template argument
2971 // values that will make the deduced A identical to A (after the type A
2972 // is transformed as described above). [...]
2973 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2974 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002975 unsigned ParamIdx = OriginalArg.ArgIdx;
2976
2977 if (ParamIdx >= Specialization->getNumParams())
2978 continue;
2979
2980 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002981 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2982 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002983 }
2984 }
2985
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002986 // If we suppressed any diagnostics while performing template argument
2987 // deduction, and if we haven't already instantiated this declaration,
2988 // keep track of these diagnostics. They'll be emitted if this specialization
2989 // is actually used.
2990 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002991 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002992 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2993 if (Pos == SuppressedDiagnostics.end())
2994 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2995 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002996 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002997
Mike Stump11289f42009-09-09 15:08:12 +00002998 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002999}
3000
John McCall8d08b9b2010-08-27 09:08:28 +00003001/// Gets the type of a function for template-argument-deducton
3002/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003003static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003004 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003005 // We may need to deduce the return type of the function now.
Alp Toker314cc812014-01-25 16:55:45 +00003006 if (S.getLangOpts().CPlusPlus1y && Fn->getReturnType()->isUndeducedType() &&
3007 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003008 return QualType();
3009
John McCallc1f69982010-02-02 02:21:27 +00003010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003011 if (Method->isInstance()) {
3012 // An instance method that's referenced in a form that doesn't
3013 // look like a member pointer is just invalid.
3014 if (!R.HasFormOfMemberPointer) return QualType();
3015
Richard Smith2a7d4812013-05-04 07:00:32 +00003016 return S.Context.getMemberPointerType(Fn->getType(),
3017 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003018 }
3019
3020 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003021 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003022}
3023
3024/// Apply the deduction rules for overload sets.
3025///
3026/// \return the null type if this argument should be treated as an
3027/// undeduced context
3028static QualType
3029ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003030 Expr *Arg, QualType ParamType,
3031 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003032
John McCall8d08b9b2010-08-27 09:08:28 +00003033 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003034
John McCall8d08b9b2010-08-27 09:08:28 +00003035 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003036
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003037 // C++0x [temp.deduct.call]p4
3038 unsigned TDF = 0;
3039 if (ParamWasReference)
3040 TDF |= TDF_ParamWithReferenceType;
3041 if (R.IsAddressOfOperand)
3042 TDF |= TDF_IgnoreQualifiers;
3043
John McCallc1f69982010-02-02 02:21:27 +00003044 // C++0x [temp.deduct.call]p6:
3045 // When P is a function type, pointer to function type, or pointer
3046 // to member function type:
3047
3048 if (!ParamType->isFunctionType() &&
3049 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003050 !ParamType->isMemberFunctionPointerType()) {
3051 if (Ovl->hasExplicitTemplateArgs()) {
3052 // But we can still look for an explicit specialization.
3053 if (FunctionDecl *ExplicitSpec
3054 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003055 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003056 }
John McCallc1f69982010-02-02 02:21:27 +00003057
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003058 return QualType();
3059 }
3060
3061 // Gather the explicit template arguments, if any.
3062 TemplateArgumentListInfo ExplicitTemplateArgs;
3063 if (Ovl->hasExplicitTemplateArgs())
3064 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003065 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003066 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3067 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003068 NamedDecl *D = (*I)->getUnderlyingDecl();
3069
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003070 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3071 // - If the argument is an overload set containing one or more
3072 // function templates, the parameter is treated as a
3073 // non-deduced context.
3074 if (!Ovl->hasExplicitTemplateArgs())
3075 return QualType();
3076
3077 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003078 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003079 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003080 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3081 Specialization, Info))
3082 continue;
3083
3084 D = Specialization;
3085 }
John McCallc1f69982010-02-02 02:21:27 +00003086
3087 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003088 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003089 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003090
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003091 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003093 ArgType->isFunctionType())
3094 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095
John McCallc1f69982010-02-02 02:21:27 +00003096 // - If the argument is an overload set (not containing function
3097 // templates), trial argument deduction is attempted using each
3098 // of the members of the set. If deduction succeeds for only one
3099 // of the overload set members, that member is used as the
3100 // argument value for the deduction. If deduction succeeds for
3101 // more than one member of the overload set the parameter is
3102 // treated as a non-deduced context.
3103
3104 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3105 // Type deduction is done independently for each P/A pair, and
3106 // the deduced template argument values are then combined.
3107 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003108 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003109 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003110 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003111 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003112 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3113 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003114 if (Result) continue;
3115 if (!Match.isNull()) return QualType();
3116 Match = ArgType;
3117 }
3118
3119 return Match;
3120}
3121
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003123/// described in C++ [temp.deduct.call].
3124///
3125/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003126/// argument deduction based on this P/A pair because the argument is an
3127/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003128static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3129 TemplateParameterList *TemplateParams,
3130 QualType &ParamType,
3131 QualType &ArgType,
3132 Expr *Arg,
3133 unsigned &TDF) {
3134 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003135 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003136 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003137 if (ParamType.hasQualifiers())
3138 ParamType = ParamType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003139 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3140 if (ParamRefType) {
Richard Smith30482bc2011-02-20 03:19:35 +00003141 QualType PointeeType = ParamRefType->getPointeeType();
3142
Richard Smith8c6eeb92013-01-31 04:03:12 +00003143 // If the argument has incomplete array type, try to complete its type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003144 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
Douglas Gregor57d4f972011-06-03 03:35:07 +00003145 ArgType = Arg->getType();
3146
Douglas Gregorcba72b12011-01-21 05:18:22 +00003147 // [C++0x] If P is an rvalue reference to a cv-unqualified
3148 // template parameter and the argument is an lvalue, the type
3149 // "lvalue reference to A" is used in place of A for type
3150 // deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003151 if (isa<RValueReferenceType>(ParamType)) {
3152 if (!PointeeType.getQualifiers() &&
3153 isa<TemplateTypeParmType>(PointeeType) &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003154 Arg->Classify(S.Context).isLValue() &&
3155 Arg->getType() != S.Context.OverloadTy &&
3156 Arg->getType() != S.Context.BoundMemberTy)
Douglas Gregorcba72b12011-01-21 05:18:22 +00003157 ArgType = S.Context.getLValueReferenceType(ArgType);
3158 }
3159
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 // [...] If P is a reference type, the type referred to by P is used
3161 // for type deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003162 ParamType = PointeeType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor7825bf32011-01-06 22:09:01 +00003165 // Overload sets usually make this parameter an undeduced
3166 // context, but there are sometimes special circumstances.
3167 if (ArgType == S.Context.OverloadTy) {
3168 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3169 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003170 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003171 if (ArgType.isNull())
3172 return true;
3173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003174
Douglas Gregor7825bf32011-01-06 22:09:01 +00003175 if (ParamRefType) {
3176 // C++0x [temp.deduct.call]p3:
3177 // [...] If P is of the form T&&, where T is a template parameter, and
3178 // the argument is an lvalue, the type A& is used in place of A for
3179 // type deduction.
3180 if (ParamRefType->isRValueReferenceType() &&
3181 ParamRefType->getAs<TemplateTypeParmType>() &&
3182 Arg->isLValue())
3183 ArgType = S.Context.getLValueReferenceType(ArgType);
3184 } else {
3185 // C++ [temp.deduct.call]p2:
3186 // If P is not a reference type:
3187 // - If A is an array type, the pointer type produced by the
3188 // array-to-pointer standard conversion (4.2) is used in place of
3189 // A for type deduction; otherwise,
3190 if (ArgType->isArrayType())
3191 ArgType = S.Context.getArrayDecayedType(ArgType);
3192 // - If A is a function type, the pointer type produced by the
3193 // function-to-pointer standard conversion (4.3) is used in place
3194 // of A for type deduction; otherwise,
3195 else if (ArgType->isFunctionType())
3196 ArgType = S.Context.getPointerType(ArgType);
3197 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003198 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003199 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003200 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003201 }
3202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Douglas Gregor7825bf32011-01-06 22:09:01 +00003204 // C++0x [temp.deduct.call]p4:
3205 // In general, the deduction process attempts to find template argument
3206 // values that will make the deduced A identical to A (after the type A
3207 // is transformed as described above). [...]
3208 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209
Douglas Gregor7825bf32011-01-06 22:09:01 +00003210 // - If the original P is a reference type, the deduced A (i.e., the
3211 // type referred to by the reference) can be more cv-qualified than
3212 // the transformed A.
3213 if (ParamRefType)
3214 TDF |= TDF_ParamWithReferenceType;
3215 // - The transformed A can be another pointer or pointer to member
3216 // type that can be converted to the deduced A via a qualification
3217 // conversion (4.4).
3218 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3219 ArgType->isObjCObjectPointerType())
3220 TDF |= TDF_IgnoreQualifiers;
3221 // - If P is a class and P has the form simple-template-id, then the
3222 // transformed A can be a derived class of the deduced A. Likewise,
3223 // if P is a pointer to a class of the form simple-template-id, the
3224 // transformed A can be a pointer to a derived class pointed to by
3225 // the deduced A.
3226 if (isSimpleTemplateIdType(ParamType) ||
3227 (isa<PointerType>(ParamType) &&
3228 isSimpleTemplateIdType(
3229 ParamType->getAs<PointerType>()->getPointeeType())))
3230 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231
Douglas Gregor7825bf32011-01-06 22:09:01 +00003232 return false;
3233}
3234
Nico Weberc153d242014-07-28 00:02:09 +00003235static bool
3236hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3237 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003238
Sebastian Redl19181662012-03-15 21:40:51 +00003239/// \brief Perform template argument deduction by matching a parameter type
3240/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003241/// an initializer list that was originally matched against a parameter
3242/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003243static Sema::TemplateDeductionResult
3244DeduceTemplateArgumentByListElement(Sema &S,
3245 TemplateParameterList *TemplateParams,
3246 QualType ParamType, Expr *Arg,
3247 TemplateDeductionInfo &Info,
3248 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3249 unsigned TDF) {
3250 // Handle the case where an init list contains another init list as the
3251 // element.
3252 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3253 QualType X;
3254 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3255 return Sema::TDK_Success; // Just ignore this expression.
3256
3257 // Recurse down into the init list.
3258 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3259 if (Sema::TemplateDeductionResult Result =
3260 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3261 ILE->getInit(i),
3262 Info, Deduced, TDF))
3263 return Result;
3264 }
3265 return Sema::TDK_Success;
3266 }
3267
3268 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003269 QualType ArgType = Arg->getType();
3270 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003271 ArgType, Arg, TDF)) {
3272 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003273 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003274 }
Sebastian Redl19181662012-03-15 21:40:51 +00003275 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003276 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003277}
3278
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003279/// \brief Perform template argument deduction from a function call
3280/// (C++ [temp.deduct.call]).
3281///
3282/// \param FunctionTemplate the function template for which we are performing
3283/// template argument deduction.
3284///
James Dennett18348b62012-06-22 08:52:37 +00003285/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003286/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003287///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003288/// \param Args the function call arguments
3289///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003290/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003291/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003292/// template argument deduction.
3293///
3294/// \param Info the argument will be updated to provide additional information
3295/// about template argument deduction.
3296///
3297/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003298Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3299 FunctionTemplateDecl *FunctionTemplate,
3300 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3301 FunctionDecl *&Specialization, TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003302 if (FunctionTemplate->isInvalidDecl())
3303 return TDK_Invalid;
3304
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003305 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00003306
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003307 // C++ [temp.deduct.call]p1:
3308 // Template argument deduction is done by comparing each function template
3309 // parameter type (call it P) with the type of the corresponding argument
3310 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003311 unsigned CheckArgs = Args.size();
3312 if (Args.size() < Function->getMinRequiredArguments())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003313 return TDK_TooFewArguments;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003314 else if (Args.size() > Function->getNumParams()) {
Mike Stump11289f42009-09-09 15:08:12 +00003315 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003316 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003317 if (Proto->isTemplateVariadic())
3318 /* Do nothing */;
3319 else if (Proto->isVariadic())
3320 CheckArgs = Function->getNumParams();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
Douglas Gregor89026b52009-06-30 23:57:56 +00003325 // The types of the parameters from which we will perform template argument
3326 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003327 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003328 TemplateParameterList *TemplateParams
3329 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 SmallVector<DeducedTemplateArgument, 4> Deduced;
3331 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003332 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003333 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003334 TemplateDeductionResult Result =
3335 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003336 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003337 Deduced,
3338 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003339 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003340 Info);
3341 if (Result)
3342 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003343
3344 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003345 } else {
3346 // Just fill in the parameter types from the function declaration.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003347 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003348 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregor89026b52009-06-30 23:57:56 +00003351 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003352 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003353 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003356 ParamIdx != NumParams; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003357 QualType OrigParamType = ParamTypes[ParamIdx];
3358 QualType ParamType = OrigParamType;
3359
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003361 = dyn_cast<PackExpansionType>(ParamType);
3362 if (!ParamExpansion) {
3363 // Simple case: matching a function parameter to a function argument.
3364 if (ArgIdx >= CheckArgs)
3365 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Douglas Gregor7825bf32011-01-06 22:09:01 +00003367 Expr *Arg = Args[ArgIdx++];
3368 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003369
Douglas Gregor7825bf32011-01-06 22:09:01 +00003370 unsigned TDF = 0;
3371 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3372 ParamType, ArgType, Arg,
3373 TDF))
3374 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregor0c83c812011-10-09 22:06:46 +00003376 // If we have nothing to deduce, we're done.
3377 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3378 continue;
3379
Sebastian Redl43144e72012-01-17 22:49:58 +00003380 // If the argument is an initializer list ...
3381 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3382 // ... then the parameter is an undeduced context, unless the parameter
3383 // type is (reference to cv) std::initializer_list<P'>, in which case
3384 // deduction is done for each element of the initializer list, and the
3385 // result is the deduced type if it's the same for all elements.
3386 QualType X;
3387 // Removing references was already done.
3388 if (!isStdInitializerList(ParamType, &X))
3389 continue;
3390
3391 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3392 if (TemplateDeductionResult Result =
Sebastian Redl19181662012-03-15 21:40:51 +00003393 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3394 ILE->getInit(i),
3395 Info, Deduced, TDF))
Sebastian Redl43144e72012-01-17 22:49:58 +00003396 return Result;
3397 }
3398 // Don't track the argument type, since an initializer list has none.
3399 continue;
3400 }
3401
Douglas Gregore65aacb2011-06-16 16:50:48 +00003402 // Keep track of the argument type and corresponding parameter index,
3403 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003404 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3405 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003406
Douglas Gregor7825bf32011-01-06 22:09:01 +00003407 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003408 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3409 ParamType, ArgType,
3410 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003411 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003412
Douglas Gregor7825bf32011-01-06 22:09:01 +00003413 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Douglas Gregor7825bf32011-01-06 22:09:01 +00003416 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 // For a function parameter pack that occurs at the end of the
3418 // parameter-declaration-list, the type A of each remaining argument of
3419 // the call is compared with the type P of the declarator-id of the
3420 // function parameter pack. Each comparison deduces template arguments
3421 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003422 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003424 // the parameter pack is a non-deduced context.
3425 if (ParamIdx + 1 < NumParams)
3426 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregor7825bf32011-01-06 22:09:01 +00003428 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003429 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3430 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Douglas Gregor7825bf32011-01-06 22:09:01 +00003432 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003433 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregore65aacb2011-06-16 16:50:48 +00003436 QualType OrigParamType = ParamPattern;
3437 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003438 Expr *Arg = Args[ArgIdx];
3439 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003440
Douglas Gregor7825bf32011-01-06 22:09:01 +00003441 unsigned TDF = 0;
3442 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3443 ParamType, ArgType, Arg,
3444 TDF)) {
3445 // We can't actually perform any deduction for this argument, so stop
3446 // deduction at this point.
3447 ++ArgIdx;
3448 break;
3449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Sebastian Redl43144e72012-01-17 22:49:58 +00003451 // As above, initializer lists need special handling.
3452 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3453 QualType X;
3454 if (!isStdInitializerList(ParamType, &X)) {
3455 ++ArgIdx;
3456 break;
3457 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003458
Sebastian Redl43144e72012-01-17 22:49:58 +00003459 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3460 if (TemplateDeductionResult Result =
3461 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3462 ILE->getInit(i)->getType(),
3463 Info, Deduced, TDF))
3464 return Result;
3465 }
3466 } else {
3467
3468 // Keep track of the argument type and corresponding argument index,
3469 // so we can check for compatibility between the deduced A and A.
3470 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3471 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3472 ArgType));
3473
3474 if (TemplateDeductionResult Result
3475 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3476 ParamType, ArgType, Info,
3477 Deduced, TDF))
3478 return Result;
3479 }
Mike Stump11289f42009-09-09 15:08:12 +00003480
Richard Smith0a80d572014-05-29 01:12:14 +00003481 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor7825bf32011-01-06 22:09:01 +00003484 // Build argument packs for each of the parameter packs expanded by this
3485 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003486 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003488
Douglas Gregor7825bf32011-01-06 22:09:01 +00003489 // After we've matching against a parameter pack, we're done.
3490 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003491 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003492
Mike Stump11289f42009-09-09 15:08:12 +00003493 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003494 NumExplicitlySpecified, Specialization,
3495 Info, &OriginalCallArgs);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003496}
3497
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003498QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3499 QualType FunctionType) {
3500 if (ArgFunctionType.isNull())
3501 return ArgFunctionType;
3502
3503 const FunctionProtoType *FunctionTypeP =
3504 FunctionType->castAs<FunctionProtoType>();
3505 CallingConv CC = FunctionTypeP->getCallConv();
3506 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3507 const FunctionProtoType *ArgFunctionTypeP =
3508 ArgFunctionType->getAs<FunctionProtoType>();
3509 if (ArgFunctionTypeP->getCallConv() == CC &&
3510 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3511 return ArgFunctionType;
3512
3513 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3514 EI = EI.withNoReturn(NoReturn);
3515 ArgFunctionTypeP =
3516 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3517 return QualType(ArgFunctionTypeP, 0);
3518}
3519
Douglas Gregor9b146582009-07-08 20:55:45 +00003520/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003521/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3522/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003523///
3524/// \param FunctionTemplate the function template for which we are performing
3525/// template argument deduction.
3526///
James Dennett18348b62012-06-22 08:52:37 +00003527/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003528/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003529///
3530/// \param ArgFunctionType the function type that will be used as the
3531/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003532/// function template's function type. This type may be NULL, if there is no
3533/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003534///
3535/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003536/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003537/// template argument deduction.
3538///
3539/// \param Info the argument will be updated to provide additional information
3540/// about template argument deduction.
3541///
3542/// \returns the result of template argument deduction.
3543Sema::TemplateDeductionResult
3544Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003545 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003546 QualType ArgFunctionType,
3547 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003548 TemplateDeductionInfo &Info,
3549 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003550 if (FunctionTemplate->isInvalidDecl())
3551 return TDK_Invalid;
3552
Douglas Gregor9b146582009-07-08 20:55:45 +00003553 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3554 TemplateParameterList *TemplateParams
3555 = FunctionTemplate->getTemplateParameters();
3556 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003557 if (!InOverloadResolution)
3558 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003559
Douglas Gregor9b146582009-07-08 20:55:45 +00003560 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003561 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003562 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003563 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003564 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003565 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003566 if (TemplateDeductionResult Result
3567 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003568 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003569 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003570 &FunctionType, Info))
3571 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003572
3573 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003574 }
3575
Eli Friedman77dcc722012-02-08 03:07:05 +00003576 // Unevaluated SFINAE context.
3577 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003578 SFINAETrap Trap(*this);
3579
John McCallc1f69982010-02-02 02:21:27 +00003580 Deduced.resize(TemplateParams->size());
3581
Richard Smith2a7d4812013-05-04 07:00:32 +00003582 // If the function has a deduced return type, substitute it for a dependent
3583 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003584 bool HasDeducedReturnType = false;
Richard Smith2a7d4812013-05-04 07:00:32 +00003585 if (getLangOpts().CPlusPlus1y && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003586 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003587 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003588 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003589 }
3590
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003591 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003592 unsigned TDF = TDF_TopLevelParameterTypeList;
3593 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003594 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003595 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003596 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003597 FunctionType, ArgFunctionType,
3598 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003599 return Result;
3600 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003601
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003603 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3604 NumExplicitlySpecified,
3605 Specialization, Info))
3606 return Result;
3607
Richard Smith2a7d4812013-05-04 07:00:32 +00003608 // If the function has a deduced return type, deduce it now, so we can check
3609 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003610 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003611 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003612 DeduceReturnType(Specialization, Info.getLocation(), false))
3613 return TDK_MiscellaneousDeductionFailure;
3614
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003615 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003616 // specialization with respect to arguments of compatible pointer to function
3617 // types, template argument deduction fails.
3618 if (!ArgFunctionType.isNull()) {
3619 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3620 Context.getCanonicalType(Specialization->getType()),
3621 Context.getCanonicalType(ArgFunctionType)))
3622 return TDK_MiscellaneousDeductionFailure;
3623 else if(!InOverloadResolution &&
3624 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3625 return TDK_MiscellaneousDeductionFailure;
3626 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003627
3628 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003629}
3630
Faisal Vali850da1a2013-09-29 17:08:32 +00003631/// \brief Given a function declaration (e.g. a generic lambda conversion
3632/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003633/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3634/// to replace 'auto' with and not the actual result type you want
3635/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003636static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003637SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003638 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003640 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003641 assert(AutoResultType->getContainedAutoType());
3642 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003643 TypeToReplaceAutoWith);
3644 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3645}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003646
3647/// \brief Given a specialized conversion operator of a generic lambda
3648/// create the corresponding specializations of the call operator and
3649/// the static-invoker. If the return type of the call operator is auto,
3650/// deduce its return type and check if that matches the
3651/// return type of the destination function ptr.
3652
3653static inline Sema::TemplateDeductionResult
3654SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3655 CXXConversionDecl *ConversionSpecialized,
3656 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3657 QualType ReturnTypeOfDestFunctionPtr,
3658 TemplateDeductionInfo &TDInfo,
3659 Sema &S) {
3660
3661 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3662 assert(LambdaClass && LambdaClass->isGenericLambda());
3663
3664 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003665 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003666 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3667 CallOpResultType->getContainedAutoType();
3668
3669 FunctionTemplateDecl *CallOpTemplate =
3670 CallOpGeneric->getDescribedFunctionTemplate();
3671
Craig Topperc3ec1492014-05-26 06:22:03 +00003672 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003673 // Use the deduced arguments of the conversion function, to specialize our
3674 // generic lambda's call operator.
3675 if (Sema::TemplateDeductionResult Result
3676 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3677 DeducedArguments,
3678 0, CallOpSpecialized, TDInfo))
3679 return Result;
3680
3681 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003682 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3683 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003684 S.DeduceReturnType(CallOpSpecialized,
3685 CallOpSpecialized->getPointOfInstantiation(),
3686 /*Diagnose*/ true);
3687
3688 // Check to see if the return type of the destination ptr-to-function
3689 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003690 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003691 ReturnTypeOfDestFunctionPtr))
3692 return Sema::TDK_NonDeducedMismatch;
3693 // Since we have succeeded in matching the source and destination
3694 // ptr-to-functions (now including return type), and have successfully
3695 // specialized our corresponding call operator, we are ready to
3696 // specialize the static invoker with the deduced arguments of our
3697 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003698 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003699 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3700 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3701
3702 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result
3703 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3704 InvokerSpecialized, TDInfo);
3705 assert(Result == Sema::TDK_Success &&
3706 "If the call operator succeeded so should the invoker!");
3707 // Set the result type to match the corresponding call operator
3708 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003709 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3710 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003711 // Be sure to get the type to replace 'auto' with and not
3712 // the full result type of the call op specialization
3713 // to substitute into the 'auto' of the invoker and conversion
3714 // function.
3715 // For e.g.
3716 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3717 // We don't want to subst 'int*' into 'auto' to get int**.
3718
Alp Toker314cc812014-01-25 16:55:45 +00003719 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3720 ->getContainedAutoType()
3721 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003722 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3723 TypeToReplaceAutoWith, S);
3724 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3725 TypeToReplaceAutoWith, S);
3726 }
3727
3728 // Ensure that static invoker doesn't have a const qualifier.
3729 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3730 // do not use the CallOperator's TypeSourceInfo which allows
3731 // the const qualifier to leak through.
3732 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3733 getType().getTypePtr()->castAs<FunctionProtoType>();
3734 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3735 EPI.TypeQuals = 0;
3736 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003737 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003738 return Sema::TDK_Success;
3739}
Douglas Gregor05155d82009-08-21 23:19:43 +00003740/// \brief Deduce template arguments for a templated conversion
3741/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3742/// conversion function template specialization.
3743Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003744Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003745 QualType ToType,
3746 CXXConversionDecl *&Specialization,
3747 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003748 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003749 return TDK_Invalid;
3750
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003752 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3753
Faisal Vali2b3a3012013-10-24 23:40:02 +00003754 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003755
3756 // Canonicalize the types for deduction.
3757 QualType P = Context.getCanonicalType(FromType);
3758 QualType A = Context.getCanonicalType(ToType);
3759
Douglas Gregord99609a2011-03-06 09:03:20 +00003760 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003761 // If P is a reference type, the type referred to by P is used for
3762 // type deduction.
3763 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3764 P = PRef->getPointeeType();
3765
Douglas Gregord99609a2011-03-06 09:03:20 +00003766 // C++0x [temp.deduct.conv]p4:
3767 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003768 // for type deduction.
3769 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003770 A = ARef->getPointeeType().getUnqualifiedType();
3771 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003772 //
Mike Stump11289f42009-09-09 15:08:12 +00003773 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003774 else {
3775 assert(!A->isReferenceType() && "Reference types were handled above");
3776
3777 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003778 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003779 // of P for type deduction; otherwise,
3780 if (P->isArrayType())
3781 P = Context.getArrayDecayedType(P);
3782 // - If P is a function type, the pointer type produced by the
3783 // function-to-pointer standard conversion (4.3) is used in
3784 // place of P for type deduction; otherwise,
3785 else if (P->isFunctionType())
3786 P = Context.getPointerType(P);
3787 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003788 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003789 else
3790 P = P.getUnqualifiedType();
3791
Douglas Gregord99609a2011-03-06 09:03:20 +00003792 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003793 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003794 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003795 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003796 A = A.getUnqualifiedType();
3797 }
3798
Eli Friedman77dcc722012-02-08 03:07:05 +00003799 // Unevaluated SFINAE context.
3800 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003801 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003802
3803 // C++ [temp.deduct.conv]p1:
3804 // Template argument deduction is done by comparing the return
3805 // type of the template conversion function (call it P) with the
3806 // type that is required as the result of the conversion (call it
3807 // A) as described in 14.8.2.4.
3808 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003809 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003810 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003811 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003812
3813 // C++0x [temp.deduct.conv]p4:
3814 // In general, the deduction process attempts to find template
3815 // argument values that will make the deduced A identical to
3816 // A. However, there are two cases that allow a difference:
3817 unsigned TDF = 0;
3818 // - If the original A is a reference type, A can be more
3819 // cv-qualified than the deduced A (i.e., the type referred to
3820 // by the reference)
3821 if (ToType->isReferenceType())
3822 TDF |= TDF_ParamWithReferenceType;
3823 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003824 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003825 // conversion.
3826 //
3827 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3828 // both P and A are pointers or member pointers. In this case, we
3829 // just ignore cv-qualifiers completely).
3830 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003831 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003832 TDF |= TDF_IgnoreQualifiers;
3833 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003834 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3835 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003836 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003837
3838 // Create an Instantiation Scope for finalizing the operator.
3839 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003840 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003841 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003842 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003843 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3844 ConversionSpecialized, Info);
3845 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3846
3847 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003848 // to a ptr-to-function, use the deduced arguments from the conversion
3849 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003850 // e.g., int (*fp)(int) = [](auto a) { return a; };
3851 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3852
3853 // Get the return type of the destination ptr-to-function we are converting
3854 // to. This is necessary for matching the lambda call operator's return
3855 // type to that of the destination ptr-to-function's return type.
3856 assert(A->isPointerType() &&
3857 "Can only convert from lambda to ptr-to-function");
3858 const FunctionType *ToFunType =
3859 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003860 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3861
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 // Create the corresponding specializations of the call operator and
3863 // the static-invoker; and if the return type is auto,
3864 // deduce the return type and check if it matches the
3865 // DestFunctionPtrReturnType.
3866 // For instance:
3867 // auto L = [](auto a) { return f(a); };
3868 // int (*fp)(int) = L;
3869 // char (*fp2)(int) = L; <-- Not OK.
3870
3871 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3872 Specialization, Deduced, DestFunctionPtrReturnType,
3873 Info, *this);
3874 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003875 return Result;
3876}
3877
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003878/// \brief Deduce template arguments for a function template when there is
3879/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3880///
3881/// \param FunctionTemplate the function template for which we are performing
3882/// template argument deduction.
3883///
James Dennett18348b62012-06-22 08:52:37 +00003884/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003885/// arguments.
3886///
3887/// \param Specialization if template argument deduction was successful,
3888/// this will be set to the function template specialization produced by
3889/// template argument deduction.
3890///
3891/// \param Info the argument will be updated to provide additional information
3892/// about template argument deduction.
3893///
3894/// \returns the result of template argument deduction.
3895Sema::TemplateDeductionResult
3896Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003897 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003898 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003899 TemplateDeductionInfo &Info,
3900 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003901 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003902 QualType(), Specialization, Info,
3903 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003904}
3905
Richard Smith30482bc2011-02-20 03:19:35 +00003906namespace {
3907 /// Substitute the 'auto' type specifier within a type for a given replacement
3908 /// type.
3909 class SubstituteAutoTransform :
3910 public TreeTransform<SubstituteAutoTransform> {
3911 QualType Replacement;
3912 public:
Nico Weberc153d242014-07-28 00:02:09 +00003913 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3914 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3915 Replacement(Replacement) {}
3916
Richard Smith30482bc2011-02-20 03:19:35 +00003917 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3918 // If we're building the type pattern to deduce against, don't wrap the
3919 // substituted type in an AutoType. Certain template deduction rules
3920 // apply only when a template type parameter appears directly (and not if
3921 // the parameter is found through desugaring). For instance:
3922 // auto &&lref = lvalue;
3923 // must transform into "rvalue reference to T" not "rvalue reference to
3924 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003925 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003926 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003927 TemplateTypeParmTypeLoc NewTL =
3928 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003929 NewTL.setNameLoc(TL.getNameLoc());
3930 return Result;
3931 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003932 bool Dependent =
3933 !Replacement.isNull() && Replacement->isDependentType();
3934 QualType Result =
3935 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3936 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003937 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003938 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3939 NewTL.setNameLoc(TL.getNameLoc());
3940 return Result;
3941 }
3942 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003943
3944 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3945 // Lambdas never need to be transformed.
3946 return E;
3947 }
Richard Smith061f1e22013-04-30 21:23:01 +00003948
Richard Smith2a7d4812013-05-04 07:00:32 +00003949 QualType Apply(TypeLoc TL) {
3950 // Create some scratch storage for the transformed type locations.
3951 // FIXME: We're just going to throw this information away. Don't build it.
3952 TypeLocBuilder TLB;
3953 TLB.reserve(TL.getFullDataSize());
3954 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003955 }
Richard Smith30482bc2011-02-20 03:19:35 +00003956 };
3957}
3958
Richard Smith2a7d4812013-05-04 07:00:32 +00003959Sema::DeduceAutoResult
3960Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3961 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3962}
3963
Richard Smith061f1e22013-04-30 21:23:01 +00003964/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003965///
3966/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003967/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003968/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003969/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003970Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003971Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003972 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003973 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3974 if (NonPlaceholder.isInvalid())
3975 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003976 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003977 }
3978
Richard Smith2a7d4812013-05-04 07:00:32 +00003979 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003980 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003981 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003982 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003983 }
3984
Richard Smith74aeef52013-04-26 16:15:35 +00003985 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3986 // Since 'decltype(auto)' can only occur at the top of the type, we
3987 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003988 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003989 if (AT->isDecltypeAuto()) {
3990 if (isa<InitListExpr>(Init)) {
3991 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3992 return DAR_FailedAlreadyDiagnosed;
3993 }
3994
3995 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart());
3996 // FIXME: Support a non-canonical deduced type for 'auto'.
3997 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003998 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003999 if (Result.isNull())
4000 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004001 return DAR_Succeeded;
4002 }
4003 }
4004
Richard Smith30482bc2011-02-20 03:19:35 +00004005 SourceLocation Loc = Init->getExprLoc();
4006
4007 LocalInstantiationScope InstScope(*this);
4008
4009 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004010 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004011 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4012 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004013 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4014 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00004015 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
4016 Loc);
4017
Richard Smith061f1e22013-04-30 21:23:01 +00004018 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4019 assert(!FuncParam.isNull() &&
4020 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004021
4022 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004023 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004024 Deduced.resize(1);
4025 QualType InitType = Init->getType();
4026 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004027
Craig Toppere6706e42012-09-19 02:26:47 +00004028 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004029
Richard Smith74801c82012-07-08 04:13:07 +00004030 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004031 if (InitList) {
4032 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004033 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004034 TemplArg,
4035 InitList->getInit(i),
4036 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004037 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004038 }
4039 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004040 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4041 FuncParam, InitType, Init,
4042 TDF))
4043 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004044
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004045 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4046 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004047 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004048 }
Richard Smith30482bc2011-02-20 03:19:35 +00004049
Eli Friedmane4310952012-11-06 23:56:42 +00004050 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004051 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004052
Eli Friedmane4310952012-11-06 23:56:42 +00004053 QualType DeducedType = Deduced[0].getAsType();
4054
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004055 if (InitList) {
4056 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4057 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004058 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004059 }
4060
Richard Smith061f1e22013-04-30 21:23:01 +00004061 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004062 if (Result.isNull())
4063 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004064
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004065 // Check that the deduced argument type is compatible with the original
4066 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004067 if (!InitList && !Result.isNull() &&
4068 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004069 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004070 Result)) {
4071 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004072 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004073 }
4074
Sebastian Redl09edce02012-01-23 22:09:39 +00004075 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004076}
4077
Faisal Vali2b391ab2013-09-26 19:54:12 +00004078QualType Sema::SubstAutoType(QualType TypeWithAuto,
4079 QualType TypeToReplaceAuto) {
4080 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4081 TransformType(TypeWithAuto);
4082}
4083
4084TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4085 QualType TypeToReplaceAuto) {
4086 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4087 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004088}
4089
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004090void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4091 if (isa<InitListExpr>(Init))
4092 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004093 VDecl->isInitCapture()
4094 ? diag::err_init_capture_deduction_failure_from_init_list
4095 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004096 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4097 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004098 Diag(VDecl->getLocation(),
4099 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4100 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004101 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4102 << Init->getSourceRange();
4103}
4104
Richard Smith2a7d4812013-05-04 07:00:32 +00004105bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4106 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004107 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004108
4109 if (FD->getTemplateInstantiationPattern())
4110 InstantiateFunctionDefinition(Loc, FD);
4111
Alp Toker314cc812014-01-25 16:55:45 +00004112 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004113 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4114 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4115 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4116 }
4117
4118 return StillUndeduced;
4119}
4120
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004121static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004122MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004123 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004124 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004125 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
4127/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004128static void
4129AddImplicitObjectParameterType(ASTContext &Context,
4130 CXXMethodDecl *Method,
4131 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004132 // C++11 [temp.func.order]p3:
4133 // [...] The new parameter is of type "reference to cv A," where cv are
4134 // the cv-qualifiers of the function template (if any) and A is
4135 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004136 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004137 // The standard doesn't say explicitly, but we pick the appropriate kind of
4138 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004139 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4140 ArgTy = Context.getQualifiedType(ArgTy,
4141 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004142 if (Method->getRefQualifier() == RQ_RValue)
4143 ArgTy = Context.getRValueReferenceType(ArgTy);
4144 else
4145 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004146 ArgTypes.push_back(ArgTy);
4147}
4148
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004149/// \brief Determine whether the function template \p FT1 is at least as
4150/// specialized as \p FT2.
4151static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004152 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004153 FunctionTemplateDecl *FT1,
4154 FunctionTemplateDecl *FT2,
4155 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004156 unsigned NumCallArguments1,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004157 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004158 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004160 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4161 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004163 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4164 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004165 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004166 Deduced.resize(TemplateParams->size());
4167
4168 // C++0x [temp.deduct.partial]p3:
4169 // The types used to determine the ordering depend on the context in which
4170 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004171 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004172 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004173 switch (TPOC) {
4174 case TPOC_Call: {
4175 // - In the context of a function call, the function parameter types are
4176 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004177 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4178 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004179
Eli Friedman3b5774a2012-09-19 23:27:04 +00004180 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004181 // [...] If only one of the function templates is a non-static
4182 // member, that function template is considered to have a new
4183 // first parameter inserted in its function parameter list. The
4184 // new parameter is of type "reference to cv A," where cv are
4185 // the cv-qualifiers of the function template (if any) and A is
4186 // the class of which the function template is a member.
4187 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004188 // Note that we interpret this to mean "if one of the function
4189 // templates is a non-static member and the other is a non-member";
4190 // otherwise, the ordering rules for static functions against non-static
4191 // functions don't make any sense.
4192 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004193 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4194 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004195 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004196
Richard Smithe5b52202013-09-11 00:52:39 +00004197 unsigned NumComparedArguments = NumCallArguments1;
4198
4199 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004200 // Compare 'this' from Method1 against first parameter from Method2.
4201 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4202 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004203 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004204 // Compare 'this' from Method2 against first parameter from Method1.
4205 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004206 }
4207
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004208 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004209 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004210 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004211 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212
Douglas Gregorb837ea42011-01-11 17:34:58 +00004213 // C++ [temp.func.order]p5:
4214 // The presence of unused ellipsis and default arguments has no effect on
4215 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004216 if (Args1.size() > NumComparedArguments)
4217 Args1.resize(NumComparedArguments);
4218 if (Args2.size() > NumComparedArguments)
4219 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004220 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4221 Args1.data(), Args1.size(), Info, Deduced,
4222 TDF_None, /*PartialOrdering=*/true,
Douglas Gregor63814022011-01-21 17:29:42 +00004223 RefParamComparisons))
Richard Smith0a80d572014-05-29 01:12:14 +00004224 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004226 break;
4227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004229 case TPOC_Conversion:
4230 // - In the context of a call to a conversion operator, the return types
4231 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004232 if (DeduceTemplateArgumentsByTypeMatch(
4233 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4234 Info, Deduced, TDF_None,
4235 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004236 return false;
4237 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004239 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004240 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004241 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004242 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4243 FD2->getType(), FD1->getType(),
4244 Info, Deduced, TDF_None,
4245 /*PartialOrdering=*/true,
4246 RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004247 return false;
4248 break;
4249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004251 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252 // In most cases, all template parameters must have values in order for
4253 // deduction to succeed, but for partial ordering purposes a template
4254 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004255 // types being used for partial ordering. [ Note: a template parameter used
4256 // in a non-deduced context is considered used. -end note]
4257 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4258 for (; ArgIdx != NumArgs; ++ArgIdx)
4259 if (Deduced[ArgIdx].isNull())
4260 break;
4261
4262 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004264 // as FT2.
4265 return true;
4266 }
4267
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004268 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004269 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004270 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004271 case TPOC_Call:
4272 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4273 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004274 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004275 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004279 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4280 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004284 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004285 TemplateParams->getDepth(),
4286 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004287 break;
4288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004290 for (; ArgIdx != NumArgs; ++ArgIdx)
4291 // If this argument had no value deduced but was used in one of the types
4292 // used for partial ordering, then deduction fails.
4293 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4294 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004296 return true;
4297}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
Douglas Gregorcef1a032011-01-16 16:03:23 +00004299/// \brief Determine whether this a function template whose parameter-type-list
4300/// ends with a function parameter pack.
4301static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4302 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4303 unsigned NumParams = Function->getNumParams();
4304 if (NumParams == 0)
4305 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregorcef1a032011-01-16 16:03:23 +00004307 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4308 if (!Last->isParameterPack())
4309 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310
Douglas Gregorcef1a032011-01-16 16:03:23 +00004311 // Make sure that no previous parameter is a parameter pack.
4312 while (--NumParams > 0) {
4313 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4314 return false;
4315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
Douglas Gregorcef1a032011-01-16 16:03:23 +00004317 return true;
4318}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregorbe999392009-09-15 16:23:51 +00004320/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004321/// to the rules of function template partial ordering (C++ [temp.func.order]).
4322///
4323/// \param FT1 the first function template
4324///
4325/// \param FT2 the second function template
4326///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327/// \param TPOC the context in which we are performing partial ordering of
4328/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004329///
Richard Smithe5b52202013-09-11 00:52:39 +00004330/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4331/// only when \c TPOC is \c TPOC_Call.
4332///
4333/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4334/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004335///
Douglas Gregorbe999392009-09-15 16:23:51 +00004336/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004337/// template is more specialized, returns NULL.
4338FunctionTemplateDecl *
4339Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4340 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004341 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004342 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004343 unsigned NumCallArguments1,
4344 unsigned NumCallArguments2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004345 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Craig Topperc3ec1492014-05-26 06:22:03 +00004347 NumCallArguments1, nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004349 NumCallArguments2,
Douglas Gregor63814022011-01-21 17:29:42 +00004350 &RefParamComparisons);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004352 if (Better1 != Better2) // We have a clear winner
4353 return Better1? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004355 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004356 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359 // If for each type being considered a given template is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004360 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361 // the other template is not more specialized for any types or is not at
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004362 // least as specialized for any types, then the given template is more
4363 // specialized than the other template. Otherwise, neither template is more
4364 // specialized than the other.
4365 Better1 = false;
4366 Better2 = false;
Douglas Gregor63814022011-01-21 17:29:42 +00004367 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004368 // C++0x [temp.deduct.partial]p9:
4369 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregor63814022011-01-21 17:29:42 +00004370 // types are identical after the transformations above) and both P and A
4371 // were reference types (before being replaced with the type referred to
4372 // above):
4373
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374 // -- if the type from the argument template was an lvalue reference
Douglas Gregor63814022011-01-21 17:29:42 +00004375 // and the type from the parameter template was not, the argument
4376 // type is considered to be more specialized than the other;
4377 // otherwise,
4378 if (!RefParamComparisons[I].ArgIsRvalueRef &&
4379 RefParamComparisons[I].ParamIsRvalueRef) {
4380 Better2 = true;
4381 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004382 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004383 continue;
4384 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
4385 RefParamComparisons[I].ArgIsRvalueRef) {
4386 Better1 = true;
4387 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004388 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004389 continue;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
Douglas Gregor63814022011-01-21 17:29:42 +00004392 // -- if the type from the argument template is more cv-qualified than
4393 // the type from the parameter template (as described above), the
4394 // argument type is considered to be more specialized than the
4395 // other; otherwise,
4396 switch (RefParamComparisons[I].Qualifiers) {
4397 case NeitherMoreQualified:
4398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor63814022011-01-21 17:29:42 +00004400 case ParamMoreQualified:
4401 Better1 = true;
4402 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004403 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004404 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregor63814022011-01-21 17:29:42 +00004406 case ArgMoreQualified:
4407 Better2 = true;
4408 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004409 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004410 continue;
4411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Douglas Gregor63814022011-01-21 17:29:42 +00004413 // -- neither type is more specialized than the other.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004416 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00004417 if (Better1)
4418 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004419 else if (Better2)
4420 return FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Douglas Gregorcef1a032011-01-16 16:03:23 +00004422 // FIXME: This mimics what GCC implements, but doesn't match up with the
4423 // proposed resolution for core issue 692. This area needs to be sorted out,
4424 // but for now we attempt to maintain compatibility.
4425 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4426 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4427 if (Variadic1 != Variadic2)
4428 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429
Craig Topperc3ec1492014-05-26 06:22:03 +00004430 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004431}
Douglas Gregor9b146582009-07-08 20:55:45 +00004432
Douglas Gregor450f00842009-09-25 18:43:00 +00004433/// \brief Determine if the two templates are equivalent.
4434static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4435 if (T1 == T2)
4436 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Douglas Gregor450f00842009-09-25 18:43:00 +00004438 if (!T1 || !T2)
4439 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440
Douglas Gregor450f00842009-09-25 18:43:00 +00004441 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4442}
4443
4444/// \brief Retrieve the most specialized of the given function template
4445/// specializations.
4446///
John McCall58cc69d2010-01-27 01:50:18 +00004447/// \param SpecBegin the start iterator of the function template
4448/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004449///
John McCall58cc69d2010-01-27 01:50:18 +00004450/// \param SpecEnd the end iterator of the function template
4451/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004452///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004454/// diagnostic should occur.
4455///
4456/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4457/// no matching candidates.
4458///
4459/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4460/// occurs.
4461///
4462/// \param CandidateDiag partial diagnostic used for each function template
4463/// specialization that is a candidate in the ambiguous ordering. One parameter
4464/// in this diagnostic should be unbound, which will correspond to the string
4465/// describing the template arguments for the function template specialization.
4466///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004468/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004469UnresolvedSetIterator Sema::getMostSpecialized(
4470 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4471 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004472 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4473 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4474 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004475 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004476 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004477 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004478 FailedCandidates.NoteCandidates(*this, Loc);
4479 }
John McCall58cc69d2010-01-27 01:50:18 +00004480 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
4483 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004484 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregor450f00842009-09-25 18:43:00 +00004486 // Find the function template that is better than all of the templates it
4487 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004488 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004490 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004491 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004492 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4493 FunctionTemplateDecl *Challenger
4494 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004496 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004497 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004498 Challenger)) {
4499 Best = I;
4500 BestTemplate = Challenger;
4501 }
4502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor450f00842009-09-25 18:43:00 +00004504 // Make sure that the "best" function template is more specialized than all
4505 // of the others.
4506 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004507 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4508 FunctionTemplateDecl *Challenger
4509 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004510 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004512 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004513 BestTemplate)) {
4514 Ambiguous = true;
4515 break;
4516 }
4517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
Douglas Gregor450f00842009-09-25 18:43:00 +00004519 if (!Ambiguous) {
4520 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004521 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
Douglas Gregor450f00842009-09-25 18:43:00 +00004524 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004525 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004526 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527
Richard Smithb875c432013-05-04 01:51:08 +00004528 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004529 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4530 PartialDiagnostic PD = CandidateDiag;
4531 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004532 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004533 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004534 if (!TargetType.isNull())
4535 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4536 TargetType);
4537 Diag((*I)->getLocation(), PD);
4538 }
Richard Smithb875c432013-05-04 01:51:08 +00004539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
John McCall58cc69d2010-01-27 01:50:18 +00004541 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004542}
4543
Douglas Gregorbe999392009-09-15 16:23:51 +00004544/// \brief Returns the more specialized class template partial specialization
4545/// according to the rules of partial ordering of class template partial
4546/// specializations (C++ [temp.class.order]).
4547///
4548/// \param PS1 the first class template partial specialization
4549///
4550/// \param PS2 the second class template partial specialization
4551///
4552/// \returns the more specialized class template partial specialization. If
4553/// neither partial specialization is more specialized, returns NULL.
4554ClassTemplatePartialSpecializationDecl *
4555Sema::getMoreSpecializedPartialSpecialization(
4556 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004557 ClassTemplatePartialSpecializationDecl *PS2,
4558 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004559 // C++ [temp.class.order]p1:
4560 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 // specialized as the second if, given the following rewrite to two
4562 // function templates, the first function template is at least as
4563 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004564 // templates (14.6.6.2):
4565 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 // first partial specialization and has a single function parameter
4567 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004568 // arguments of the first partial specialization, and
4569 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570 // second partial specialization and has a single function parameter
4571 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004572 // arguments of the second partial specialization.
4573 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004574 // Rather than synthesize function templates, we merely perform the
4575 // equivalent partial ordering by performing deduction directly on
4576 // the template arguments of the class template partial
4577 // specializations. This computation is slightly simpler than the
4578 // general problem of function template partial ordering, because
4579 // class template partial specializations are more constrained. We
4580 // know that every template parameter is deducible from the class
4581 // template partial specialization's template arguments, for
4582 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004583 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004584 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004585
4586 QualType PT1 = PS1->getInjectedSpecializationType();
4587 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004588
Douglas Gregorbe999392009-09-15 16:23:51 +00004589 // Determine whether PS1 is at least as specialized as PS2
4590 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004591 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4592 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004593 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004595 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004596 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004597 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004598 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004599 Better1 = !::FinishTemplateArgumentDeduction(
4600 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4601 }
4602
4603 // Determine whether PS2 is at least as specialized as PS1
4604 Deduced.clear();
4605 Deduced.resize(PS1->getTemplateParameters()->size());
4606 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4607 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4608 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004609 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004610 if (Better2) {
4611 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4612 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004613 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004614 Better2 = !::FinishTemplateArgumentDeduction(
4615 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4616 }
4617
4618 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004619 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004620
4621 return Better1 ? PS1 : PS2;
4622}
4623
Larisse Voufo30616382013-08-23 22:21:36 +00004624/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4625/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4626/// VarTemplate(Partial)SpecializationDecl with a new data
4627/// structure Template(Partial)SpecializationDecl, and
4628/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004629VarTemplatePartialSpecializationDecl *
4630Sema::getMoreSpecializedPartialSpecialization(
4631 VarTemplatePartialSpecializationDecl *PS1,
4632 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4633 SmallVector<DeducedTemplateArgument, 4> Deduced;
4634 TemplateDeductionInfo Info(Loc);
4635
Richard Smithf04fd0b2013-12-12 23:14:16 +00004636 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004637 "the partial specializations being compared should specialize"
4638 " the same template.");
4639 TemplateName Name(PS1->getSpecializedTemplate());
4640 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4641 QualType PT1 = Context.getTemplateSpecializationType(
4642 CanonTemplate, PS1->getTemplateArgs().data(),
4643 PS1->getTemplateArgs().size());
4644 QualType PT2 = Context.getTemplateSpecializationType(
4645 CanonTemplate, PS2->getTemplateArgs().data(),
4646 PS2->getTemplateArgs().size());
4647
4648 // Determine whether PS1 is at least as specialized as PS2
4649 Deduced.resize(PS2->getTemplateParameters()->size());
4650 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4651 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4652 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004653 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004654 if (Better1) {
4655 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4656 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004657 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4659 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004660 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregorbe999392009-09-15 16:23:51 +00004663 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004664 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004665 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004666 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4667 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004668 PT1, PT2, Info, Deduced, TDF_None,
4669 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004670 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004671 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004672 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004673 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4675 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004676 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004678
Douglas Gregorbe999392009-09-15 16:23:51 +00004679 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004680 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681
Douglas Gregorbe999392009-09-15 16:23:51 +00004682 return Better1? PS1 : PS2;
4683}
4684
Mike Stump11289f42009-09-09 15:08:12 +00004685static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004686MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004687 const TemplateArgument &TemplateArg,
4688 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004689 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004690 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004691
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004692/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004693/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004694static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004695MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004696 const Expr *E,
4697 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004698 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004699 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004700 // We can deduce from a pack expansion.
4701 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4702 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004703
Richard Smith34349002012-07-09 03:07:20 +00004704 // Skip through any implicit casts we added while type-checking, and any
4705 // substitutions performed by template alias expansion.
4706 while (1) {
4707 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4708 E = ICE->getSubExpr();
4709 else if (const SubstNonTypeTemplateParmExpr *Subst =
4710 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4711 E = Subst->getReplacement();
4712 else
4713 break;
4714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715
4716 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004717 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004718 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004719 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004720 return;
4721
Mike Stump11289f42009-09-09 15:08:12 +00004722 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004723 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4724 if (!NTTP)
4725 return;
4726
Douglas Gregor21610382009-10-29 00:04:11 +00004727 if (NTTP->getDepth() == Depth)
4728 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004729}
4730
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004731/// \brief Mark the template parameters that are used by the given
4732/// nested name specifier.
4733static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004734MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004735 NestedNameSpecifier *NNS,
4736 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004737 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004738 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004739 if (!NNS)
4740 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004742 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004743 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004744 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004745 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004746}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004747
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004748/// \brief Mark the template parameters that are used by the given
4749/// template name.
4750static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004751MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 TemplateName Name,
4753 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004754 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004755 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004756 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4757 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004758 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4759 if (TTP->getDepth() == Depth)
4760 Used[TTP->getIndex()] = true;
4761 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004762 return;
4763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004765 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004766 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004767 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004768 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004769 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004770 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004771}
4772
4773/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004774/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004775static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004776MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004777 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004778 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004779 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004780 if (T.isNull())
4781 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Douglas Gregor91772d12009-06-13 00:26:55 +00004783 // Non-dependent types have nothing deducible
4784 if (!T->isDependentType())
4785 return;
4786
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004787 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004788 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004789 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004790 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004791 cast<PointerType>(T)->getPointeeType(),
4792 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004793 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004794 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004795 break;
4796
4797 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004798 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004799 cast<BlockPointerType>(T)->getPointeeType(),
4800 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004801 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004802 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004803 break;
4804
4805 case Type::LValueReference:
4806 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004807 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004808 cast<ReferenceType>(T)->getPointeeType(),
4809 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004810 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004811 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004812 break;
4813
4814 case Type::MemberPointer: {
4815 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004816 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004817 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004818 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004819 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004820 break;
4821 }
4822
4823 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004824 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004825 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004826 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004827 // Fall through to check the element type
4828
4829 case Type::ConstantArray:
4830 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004832 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004833 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004834 break;
4835
4836 case Type::Vector:
4837 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004838 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004839 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004840 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004841 break;
4842
Douglas Gregor758a8692009-06-17 21:51:59 +00004843 case Type::DependentSizedExtVector: {
4844 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004845 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004846 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004847 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004848 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004849 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004850 break;
4851 }
4852
Douglas Gregor91772d12009-06-13 00:26:55 +00004853 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004854 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004855 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4856 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004857 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4858 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004859 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004860 break;
4861 }
4862
Douglas Gregor21610382009-10-29 00:04:11 +00004863 case Type::TemplateTypeParm: {
4864 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4865 if (TTP->getDepth() == Depth)
4866 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004867 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004868 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004869
Douglas Gregorfb322d82011-01-14 05:11:40 +00004870 case Type::SubstTemplateTypeParmPack: {
4871 const SubstTemplateTypeParmPackType *Subst
4872 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004873 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004874 QualType(Subst->getReplacedParameter(), 0),
4875 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004876 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004877 OnlyDeduced, Depth, Used);
4878 break;
4879 }
4880
John McCall2408e322010-04-27 00:57:59 +00004881 case Type::InjectedClassName:
4882 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4883 // fall through
4884
Douglas Gregor91772d12009-06-13 00:26:55 +00004885 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004886 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004887 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004888 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004889 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004890
Douglas Gregord0ad2942010-12-23 01:24:45 +00004891 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004892 // If the template argument list of P contains a pack expansion that is
4893 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004894 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004896 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4897 break;
4898
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004899 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004900 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004901 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004902 break;
4903 }
4904
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004905 case Type::Complex:
4906 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004908 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004909 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004910 break;
4911
Eli Friedman0dfb8892011-10-06 23:00:33 +00004912 case Type::Atomic:
4913 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004914 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004915 cast<AtomicType>(T)->getValueType(),
4916 OnlyDeduced, Depth, Used);
4917 break;
4918
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004919 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004920 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004921 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004922 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004923 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004924 break;
4925
John McCallc392f372010-06-11 00:33:02 +00004926 case Type::DependentTemplateSpecialization: {
4927 const DependentTemplateSpecializationType *Spec
4928 = cast<DependentTemplateSpecializationType>(T);
4929 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004930 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004931 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregord0ad2942010-12-23 01:24:45 +00004933 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 // If the template argument list of P contains a pack expansion that is not
4935 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004936 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004938 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4939 break;
4940
John McCallc392f372010-06-11 00:33:02 +00004941 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004942 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004943 Used);
4944 break;
4945 }
4946
John McCallbd8d9bd2010-03-01 23:49:17 +00004947 case Type::TypeOf:
4948 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004949 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004950 cast<TypeOfType>(T)->getUnderlyingType(),
4951 OnlyDeduced, Depth, Used);
4952 break;
4953
4954 case Type::TypeOfExpr:
4955 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004956 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004957 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4958 OnlyDeduced, Depth, Used);
4959 break;
4960
4961 case Type::Decltype:
4962 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004963 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004964 cast<DecltypeType>(T)->getUnderlyingExpr(),
4965 OnlyDeduced, Depth, Used);
4966 break;
4967
Alexis Hunte852b102011-05-24 22:41:36 +00004968 case Type::UnaryTransform:
4969 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004970 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004971 cast<UnaryTransformType>(T)->getUnderlyingType(),
4972 OnlyDeduced, Depth, Used);
4973 break;
4974
Douglas Gregord2fa7662010-12-20 02:24:11 +00004975 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004976 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004977 cast<PackExpansionType>(T)->getPattern(),
4978 OnlyDeduced, Depth, Used);
4979 break;
4980
Richard Smith30482bc2011-02-20 03:19:35 +00004981 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004982 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004983 cast<AutoType>(T)->getDeducedType(),
4984 OnlyDeduced, Depth, Used);
4985
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004986 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004987 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004988 case Type::VariableArray:
4989 case Type::FunctionNoProto:
4990 case Type::Record:
4991 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004993 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004994 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004995 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004996#define TYPE(Class, Base)
4997#define ABSTRACT_TYPE(Class, Base)
4998#define DEPENDENT_TYPE(Class, Base)
4999#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5000#include "clang/AST/TypeNodes.def"
5001 break;
5002 }
5003}
5004
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005005/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005006/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005007static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005008MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005009 const TemplateArgument &TemplateArg,
5010 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005011 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005012 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005013 switch (TemplateArg.getKind()) {
5014 case TemplateArgument::Null:
5015 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005016 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005017 break;
Mike Stump11289f42009-09-09 15:08:12 +00005018
Eli Friedmanb826a002012-09-26 02:36:12 +00005019 case TemplateArgument::NullPtr:
5020 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5021 Depth, Used);
5022 break;
5023
Douglas Gregor91772d12009-06-13 00:26:55 +00005024 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005025 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005026 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005027 break;
5028
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005029 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005030 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005031 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005033 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005034 break;
5035
5036 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005037 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005038 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005039 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040
Anders Carlssonbc343912009-06-15 17:04:53 +00005041 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005042 for (const auto &P : TemplateArg.pack_elements())
5043 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005044 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005045 }
5046}
5047
James Dennett41725122012-06-22 10:16:05 +00005048/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005049/// template argument list.
5050///
5051/// \param TemplateArgs the template argument list from which template
5052/// parameters will be deduced.
5053///
James Dennett41725122012-06-22 10:16:05 +00005054/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005055/// to indicate when the corresponding template parameter will be
5056/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005057void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005058Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005059 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005060 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005061 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062 // If the template argument list of P contains a pack expansion that is not
5063 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005064 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005066 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5067 return;
5068
Douglas Gregor91772d12009-06-13 00:26:55 +00005069 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005070 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005071 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005072}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005073
5074/// \brief Marks all of the template parameters that will be deduced by a
5075/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005076void Sema::MarkDeducedTemplateParameters(
5077 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5078 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005080 = FunctionTemplate->getTemplateParameters();
5081 Deduced.clear();
5082 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Douglas Gregorce23bae2009-09-18 23:21:38 +00005084 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5085 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005086 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005087 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005088}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005089
5090bool hasDeducibleTemplateParameters(Sema &S,
5091 FunctionTemplateDecl *FunctionTemplate,
5092 QualType T) {
5093 if (!T->isDependentType())
5094 return false;
5095
5096 TemplateParameterList *TemplateParams
5097 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005098 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005099 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005100 Deduced);
5101
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005102 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005103}