blob: 89b047982655542146ed23263dc01cd7862be7ee [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 &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000266 return X;
267
268 // All other combinations are incompatible.
269 return DeducedTemplateArgument();
270
271 case TemplateArgument::NullPtr:
272 // If we deduced a null pointer and a dependent expression, keep the
273 // null pointer.
274 if (Y.getKind() == TemplateArgument::Expression)
275 return X;
276
277 // If we deduced a null pointer and an integral constant, keep the
278 // integral constant.
279 if (Y.getKind() == TemplateArgument::Integral)
280 return Y;
281
282 // If we deduced two null pointers, make sure they have the same type.
283 if (Y.getKind() == TemplateArgument::NullPtr &&
284 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000287 // All other combinations are incompatible.
288 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000290 case TemplateArgument::Pack:
291 if (Y.getKind() != TemplateArgument::Pack ||
292 X.pack_size() != Y.pack_size())
293 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
295 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000296 XAEnd = X.pack_end(),
297 YA = Y.pack_begin();
298 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000299 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000300 if (checkDeducedTemplateArguments(Context,
301 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000302 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
303 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304 return DeducedTemplateArgument();
305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 return X;
308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
David Blaikiee4d798f2012-01-20 21:50:17 +0000310 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311}
312
Mike Stump11289f42009-09-09 15:08:12 +0000313/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000314/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000315static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000317 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000318 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000319 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000320 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000322 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000323 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000324
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000325 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
326 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Deduced[NTTP->getIndex()],
329 NewDeduced);
330 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000331 Info.Param = NTTP;
332 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000337 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000338 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000339}
340
Mike Stump11289f42009-09-09 15:08:12 +0000341/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000342/// from the given type- or value-dependent expression.
343///
344/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000345static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000346DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000347 NonTypeTemplateParmDecl *NTTP,
348 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000349 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000351 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000352 "Cannot deduce non-type template argument with depth > 0");
353 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
354 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000355
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000356 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
358 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000359 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000361 if (Result.isNull()) {
362 Info.Param = NTTP;
363 Info.FirstArg = Deduced[NTTP->getIndex()];
364 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000368 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000369 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000370}
371
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000372/// \brief Deduce the value of the given non-type template parameter
373/// from the given declaration.
374///
375/// \returns true if deduction succeeded, false otherwise.
376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000378 NonTypeTemplateParmDecl *NTTP,
379 ValueDecl *D,
380 TemplateDeductionInfo &Info,
381 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000382 assert(NTTP->getDepth() == 0 &&
383 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Craig Topperc3ec1492014-05-26 06:22:03 +0000385 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000386 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000387 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000389 Deduced[NTTP->getIndex()],
390 NewDeduced);
391 if (Result.isNull()) {
392 Info.Param = NTTP;
393 Info.FirstArg = Deduced[NTTP->getIndex()];
394 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000398 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000399 return Sema::TDK_Success;
400}
401
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000402static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000403DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000404 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405 TemplateName Param,
406 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000407 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000408 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000409 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000410 if (!ParamDecl) {
411 // The parameter type is dependent and is not a template template parameter,
412 // so there is nothing that we can deduce.
413 return Sema::TDK_Success;
414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
Douglas Gregoradee3e32009-11-11 23:06:43 +0000416 if (TemplateTemplateParmDecl *TempParam
417 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000418 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000420 Deduced[TempParam->getIndex()],
421 NewDeduced);
422 if (Result.isNull()) {
423 Info.Param = TempParam;
424 Info.FirstArg = Deduced[TempParam->getIndex()];
425 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000429 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000430 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Douglas Gregoradee3e32009-11-11 23:06:43 +0000433 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000434 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
Douglas Gregoradee3e32009-11-11 23:06:43 +0000437 // Mismatch of non-dependent template parameter to argument.
438 Info.FirstArg = TemplateArgument(Param);
439 Info.SecondArg = TemplateArgument(Arg);
440 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000441}
442
Mike Stump11289f42009-09-09 15:08:12 +0000443/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444/// type (which is a template-id) with the template argument type.
445///
Chandler Carruthc1263112010-02-07 21:33:28 +0000446/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000447///
448/// \param TemplateParams the template parameters that we are deducing
449///
450/// \param Param the parameter type
451///
452/// \param Arg the argument type
453///
454/// \param Info information about the template argument deduction itself
455///
456/// \param Deduced the deduced template arguments
457///
458/// \returns the result of template argument deduction so far. Note that a
459/// "success" result means that template argument deduction has not yet failed,
460/// but it may still fail, later, for other reasons.
461static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000462DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000463 TemplateParameterList *TemplateParams,
464 const TemplateSpecializationType *Param,
465 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000466 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000467 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000468 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000469
Douglas Gregore81f3e72009-07-07 23:09:34 +0000470 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000471 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 = dyn_cast<TemplateSpecializationType>(Arg)) {
473 // Perform template argument deduction for the template name.
474 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000475 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000476 Param->getTemplateName(),
477 SpecArg->getTemplateName(),
478 Info, Deduced))
479 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Mike Stump11289f42009-09-09 15:08:12 +0000481
Douglas Gregore81f3e72009-07-07 23:09:34 +0000482 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000483 // argument. Ignore any missing/extra arguments, since they could be
484 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 return DeduceTemplateArguments(S, TemplateParams,
486 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000487 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000488 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000489 }
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregore81f3e72009-07-07 23:09:34 +0000491 // If the argument type is a class template specialization, we
492 // perform template argument deduction using its template
493 // arguments.
494 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000495 if (!RecordArg) {
496 Info.FirstArg = TemplateArgument(QualType(Param, 0));
497 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
501 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000502 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000503 if (!SpecArg) {
504 Info.FirstArg = TemplateArgument(QualType(Param, 0));
505 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregore81f3e72009-07-07 23:09:34 +0000509 // Perform template argument deduction for the template name.
510 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000511 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000512 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000513 Param->getTemplateName(),
514 TemplateName(SpecArg->getSpecializedTemplate()),
515 Info, Deduced))
516 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregor7baabef2010-12-22 18:17:10 +0000518 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000520 Param->getArgs(), Param->getNumArgs(),
521 SpecArg->getTemplateArgs().data(),
522 SpecArg->getTemplateArgs().size(),
523 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524}
525
John McCall08569062010-08-28 22:14:41 +0000526/// \brief Determines whether the given type is an opaque type that
527/// might be more qualified when instantiated.
528static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
529 switch (T->getTypeClass()) {
530 case Type::TypeOfExpr:
531 case Type::TypeOf:
532 case Type::DependentName:
533 case Type::Decltype:
534 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000535 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000536 return true;
537
538 case Type::ConstantArray:
539 case Type::IncompleteArray:
540 case Type::VariableArray:
541 case Type::DependentSizedArray:
542 return IsPossiblyOpaquelyQualifiedType(
543 cast<ArrayType>(T)->getElementType());
544
545 default:
546 return false;
547 }
548}
549
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000550/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000552getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
554 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor5499af42011-01-05 23:12:31 +0000556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
561}
562
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000563/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000565getDepthAndIndex(UnexpandedParameterPack UPP) {
566 if (const TemplateTypeParmType *TTP
567 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
568 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
571}
572
Douglas Gregor5499af42011-01-05 23:12:31 +0000573/// \brief Helper function to build a TemplateParameter when we don't
574/// know its type statically.
575static TemplateParameter makeTemplateParameter(Decl *D) {
576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
577 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000579 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor5499af42011-01-05 23:12:31 +0000581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
582}
583
Richard Smith0a80d572014-05-29 01:12:14 +0000584/// A pack that we're currently deducing.
585struct clang::DeducedPack {
586 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000587
Richard Smith0a80d572014-05-29 01:12:14 +0000588 // The index of the pack.
589 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith0a80d572014-05-29 01:12:14 +0000591 // The old value of the pack before we started deducing it.
592 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // A deferred value of this pack from an inner deduction, that couldn't be
595 // deduced because this deduction hadn't happened yet.
596 DeducedTemplateArgument DeferredDeduction;
597
598 // The new value of the pack.
599 SmallVector<DeducedTemplateArgument, 4> New;
600
601 // The outer deduction for this pack, if any.
602 DeducedPack *Outer;
603};
604
605/// A scope in which we're performing pack deduction.
606class PackDeductionScope {
607public:
608 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
609 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
610 TemplateDeductionInfo &Info, TemplateArgument Pattern)
611 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
612 // Compute the set of template parameter indices that correspond to
613 // parameter packs expanded by the pack expansion.
614 {
615 llvm::SmallBitVector SawIndices(TemplateParams->size());
616 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
617 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
618 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
619 unsigned Depth, Index;
620 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
621 if (Depth == 0 && !SawIndices[Index]) {
622 SawIndices[Index] = true;
623
624 // Save the deduced template argument for the parameter pack expanded
625 // by this pack expansion, then clear out the deduction.
626 DeducedPack Pack(Index);
627 Pack.Saved = Deduced[Index];
628 Deduced[Index] = TemplateArgument();
629
630 Packs.push_back(Pack);
631 }
632 }
633 }
634 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
635
636 for (auto &Pack : Packs) {
637 if (Info.PendingDeducedPacks.size() > Pack.Index)
638 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
639 else
640 Info.PendingDeducedPacks.resize(Pack.Index + 1);
641 Info.PendingDeducedPacks[Pack.Index] = &Pack;
642
643 if (S.CurrentInstantiationScope) {
644 // If the template argument pack was explicitly specified, add that to
645 // the set of deduced arguments.
646 const TemplateArgument *ExplicitArgs;
647 unsigned NumExplicitArgs;
648 NamedDecl *PartiallySubstitutedPack =
649 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
650 &ExplicitArgs, &NumExplicitArgs);
651 if (PartiallySubstitutedPack &&
652 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
653 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
654 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000655 }
656 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000657
Richard Smith0a80d572014-05-29 01:12:14 +0000658 ~PackDeductionScope() {
659 for (auto &Pack : Packs)
660 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Richard Smith0a80d572014-05-29 01:12:14 +0000663 /// Move to deducing the next element in each pack that is being deduced.
664 void nextPackElement() {
665 // Capture the deduced template arguments for each parameter pack expanded
666 // by this pack expansion, add them to the list of arguments we've deduced
667 // for that pack, then clear out the deduced argument.
668 for (auto &Pack : Packs) {
669 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
670 if (!DeducedArg.isNull()) {
671 Pack.New.push_back(DeducedArg);
672 DeducedArg = DeducedTemplateArgument();
673 }
674 }
675 }
676
677 /// \brief Finish template argument deduction for a set of argument packs,
678 /// producing the argument packs and checking for consistency with prior
679 /// deductions.
680 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
681 // Build argument packs for each of the parameter packs expanded by this
682 // pack expansion.
683 for (auto &Pack : Packs) {
684 // Put back the old value for this pack.
685 Deduced[Pack.Index] = Pack.Saved;
686
687 // Build or find a new value for this pack.
688 DeducedTemplateArgument NewPack;
689 if (HasAnyArguments && Pack.New.empty()) {
690 if (Pack.DeferredDeduction.isNull()) {
691 // We were not able to deduce anything for this parameter pack
692 // (because it only appeared in non-deduced contexts), so just
693 // restore the saved argument pack.
694 continue;
695 }
696
697 NewPack = Pack.DeferredDeduction;
698 Pack.DeferredDeduction = TemplateArgument();
699 } else if (Pack.New.empty()) {
700 // If we deduced an empty argument pack, create it now.
701 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
702 } else {
703 TemplateArgument *ArgumentPack =
704 new (S.Context) TemplateArgument[Pack.New.size()];
705 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
706 NewPack = DeducedTemplateArgument(
707 TemplateArgument(ArgumentPack, Pack.New.size()),
708 Pack.New[0].wasDeducedFromArrayBound());
709 }
710
711 // Pick where we're going to put the merged pack.
712 DeducedTemplateArgument *Loc;
713 if (Pack.Outer) {
714 if (Pack.Outer->DeferredDeduction.isNull()) {
715 // Defer checking this pack until we have a complete pack to compare
716 // it against.
717 Pack.Outer->DeferredDeduction = NewPack;
718 continue;
719 }
720 Loc = &Pack.Outer->DeferredDeduction;
721 } else {
722 Loc = &Deduced[Pack.Index];
723 }
724
725 // Check the new pack matches any previous value.
726 DeducedTemplateArgument OldPack = *Loc;
727 DeducedTemplateArgument Result =
728 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
729
730 // If we deferred a deduction of this pack, check that one now too.
731 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
732 OldPack = Result;
733 NewPack = Pack.DeferredDeduction;
734 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
735 }
736
737 if (Result.isNull()) {
738 Info.Param =
739 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
740 Info.FirstArg = OldPack;
741 Info.SecondArg = NewPack;
742 return Sema::TDK_Inconsistent;
743 }
744
745 *Loc = Result;
746 }
747
748 return Sema::TDK_Success;
749 }
750
751private:
752 Sema &S;
753 TemplateParameterList *TemplateParams;
754 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
755 TemplateDeductionInfo &Info;
756
757 SmallVector<DeducedPack, 2> Packs;
758};
Douglas Gregorb94a6172011-01-10 17:53:52 +0000759
Douglas Gregor5499af42011-01-05 23:12:31 +0000760/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000761/// types to the list of argument types, as in the parameter-type-lists of
762/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000763///
764/// \param S The semantic analysis object within which we are deducing
765///
766/// \param TemplateParams The template parameters that we are deducing
767///
768/// \param Params The list of parameter types
769///
770/// \param NumParams The number of types in \c Params
771///
772/// \param Args The list of argument types
773///
774/// \param NumArgs The number of types in \c Args
775///
776/// \param Info information about the template argument deduction itself
777///
778/// \param Deduced the deduced template arguments
779///
780/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
781/// how template argument deduction is performed.
782///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000783/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000785/// (C++0x [temp.deduct.partial]).
786///
Douglas Gregor63814022011-01-21 17:29:42 +0000787/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000788/// in the context of partial ordering, the set of qualifier comparisons.
789///
Douglas Gregor5499af42011-01-05 23:12:31 +0000790/// \returns the result of template argument deduction so far. Note that a
791/// "success" result means that template argument deduction has not yet failed,
792/// but it may still fail, later, for other reasons.
793static Sema::TemplateDeductionResult
794DeduceTemplateArguments(Sema &S,
795 TemplateParameterList *TemplateParams,
796 const QualType *Params, unsigned NumParams,
797 const QualType *Args, unsigned NumArgs,
798 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000799 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000800 unsigned TDF,
801 bool PartialOrdering = false,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000802 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 RefParamComparisons = nullptr) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000804 // Fast-path check to see if we have too many/too few arguments.
805 if (NumParams != NumArgs &&
806 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
807 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000808 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809
Douglas Gregor5499af42011-01-05 23:12:31 +0000810 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811 // Similarly, if P has a form that contains (T), then each parameter type
812 // Pi of the respective parameter-type- list of P is compared with the
813 // corresponding parameter type Ai of the corresponding parameter-type-list
814 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000815 unsigned ArgIdx = 0, ParamIdx = 0;
816 for (; ParamIdx != NumParams; ++ParamIdx) {
817 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000819 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
820 if (!Expansion) {
821 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Douglas Gregor5499af42011-01-05 23:12:31 +0000823 // Make sure we have an argument.
824 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000825 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000827 if (isa<PackExpansionType>(Args[ArgIdx])) {
828 // C++0x [temp.deduct.type]p22:
829 // If the original function parameter associated with A is a function
830 // parameter pack and the function parameter associated with P is not
831 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000832 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor5499af42011-01-05 23:12:31 +0000835 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000836 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
837 Params[ParamIdx], Args[ArgIdx],
838 Info, Deduced, TDF,
839 PartialOrdering,
840 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 ++ArgIdx;
844 continue;
845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000847 // C++0x [temp.deduct.type]p5:
848 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000850 // parameter-declaration-clause.
851 if (ParamIdx + 1 < NumParams)
852 return Sema::TDK_Success;
853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 // comparison deduces template arguments for subsequent positions in the
859 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000862 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 bool HasAnyArguments = false;
865 for (; ArgIdx < NumArgs; ++ArgIdx) {
866 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
871 Args[ArgIdx], Info, Deduced,
872 TDF, PartialOrdering,
873 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000874 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875
Richard Smith0a80d572014-05-29 01:12:14 +0000876 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Douglas Gregor5499af42011-01-05 23:12:31 +0000879 // Build argument packs for each of the parameter packs expanded by this
880 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000881 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Douglas Gregor5499af42011-01-05 23:12:31 +0000885 // Make sure we don't have any extra arguments.
886 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000887 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5499af42011-01-05 23:12:31 +0000889 return Sema::TDK_Success;
890}
891
Douglas Gregor1d684c22011-04-28 00:56:09 +0000892/// \brief Determine whether the parameter has qualifiers that are either
893/// inconsistent with or a superset of the argument's qualifiers.
894static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
895 QualType ArgType) {
896 Qualifiers ParamQs = ParamType.getQualifiers();
897 Qualifiers ArgQs = ArgType.getQualifiers();
898
899 if (ParamQs == ArgQs)
900 return false;
901
902 // Mismatched (but not missing) Objective-C GC attributes.
903 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
904 ParamQs.hasObjCGCAttr())
905 return true;
906
907 // Mismatched (but not missing) address spaces.
908 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
909 ParamQs.hasAddressSpace())
910 return true;
911
John McCall31168b02011-06-15 23:02:42 +0000912 // Mismatched (but not missing) Objective-C lifetime qualifiers.
913 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
914 ParamQs.hasObjCLifetime())
915 return true;
916
Douglas Gregor1d684c22011-04-28 00:56:09 +0000917 // CVR qualifier superset.
918 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
919 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
920 == ParamQs.getCVRQualifiers());
921}
922
Douglas Gregor19a41f12013-04-17 08:45:07 +0000923/// \brief Compare types for equality with respect to possibly compatible
924/// function types (noreturn adjustment, implicit calling conventions). If any
925/// of parameter and argument is not a function, just perform type comparison.
926///
927/// \param Param the template parameter type.
928///
929/// \param Arg the argument type.
930bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
931 CanQualType Arg) {
932 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
933 *ArgFunction = Arg->getAs<FunctionType>();
934
935 // Just compare if not functions.
936 if (!ParamFunction || !ArgFunction)
937 return Param == Arg;
938
939 // Noreturn adjustment.
940 QualType AdjustedParam;
941 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
942 return Arg == Context.getCanonicalType(AdjustedParam);
943
944 // FIXME: Compatible calling conventions.
945
946 return Param == Arg;
947}
948
Douglas Gregorcceb9752009-06-26 18:27:22 +0000949/// \brief Deduce the template arguments by comparing the parameter type and
950/// the argument type (C++ [temp.deduct.type]).
951///
Chandler Carruthc1263112010-02-07 21:33:28 +0000952/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000953///
954/// \param TemplateParams the template parameters that we are deducing
955///
956/// \param ParamIn the parameter type
957///
958/// \param ArgIn the argument type
959///
960/// \param Info information about the template argument deduction itself
961///
962/// \param Deduced the deduced template arguments
963///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000964/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000965/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000966///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000967/// \param PartialOrdering Whether we're performing template argument deduction
968/// in the context of partial ordering (C++0x [temp.deduct.partial]).
969///
Douglas Gregor63814022011-01-21 17:29:42 +0000970/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000971/// in the context of partial ordering, the set of qualifier comparisons.
972///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000973/// \returns the result of template argument deduction so far. Note that a
974/// "success" result means that template argument deduction has not yet failed,
975/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000976static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000977DeduceTemplateArgumentsByTypeMatch(Sema &S,
978 TemplateParameterList *TemplateParams,
979 QualType ParamIn, QualType ArgIn,
980 TemplateDeductionInfo &Info,
981 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
982 unsigned TDF,
983 bool PartialOrdering,
984 SmallVectorImpl<RefParamPartialOrderingComparison> *
985 RefParamComparisons) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000986 // We only want to look at the canonical types, since typedefs and
987 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000988 QualType Param = S.Context.getCanonicalType(ParamIn);
989 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000990
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000991 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000993 if (const PackExpansionType *ArgExpansion
994 = dyn_cast<PackExpansionType>(Arg))
995 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregorb837ea42011-01-11 17:34:58 +0000997 if (PartialOrdering) {
998 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999 // Before the partial ordering is done, certain transformations are
1000 // performed on the types used for partial ordering:
1001 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1003 if (ParamRef)
1004 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
Douglas Gregorb837ea42011-01-11 17:34:58 +00001006 // - If A is a reference type, A is replaced by the type referred to.
1007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1008 if (ArgRef)
1009 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor63814022011-01-21 17:29:42 +00001011 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregorb837ea42011-01-11 17:34:58 +00001012 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013 // If both P and A were reference types (before being replaced with the
1014 // type referred to above), determine which of the two types (if any) is
Douglas Gregorb837ea42011-01-11 17:34:58 +00001015 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregorb837ea42011-01-11 17:34:58 +00001017 // of this determination will be used below.
1018 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 // We save this information for later, using it only when deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +00001020 // succeeds in both directions.
Douglas Gregor63814022011-01-21 17:29:42 +00001021 RefParamPartialOrderingComparison Comparison;
1022 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
1023 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
1024 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001025
1026 Qualifiers ParamQuals = Param.getQualifiers();
1027 Qualifiers ArgQuals = Arg.getQualifiers();
1028 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001029 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001030 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001031 Comparison.Qualifiers = ArgMoreQualified;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001032 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() &&
1033 ArgQuals.withoutObjCLifetime()
1034 == ParamQuals.withoutObjCLifetime()) {
1035 // Prefer binding to non-__unsafe_autoretained parameters.
1036 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1037 ParamQuals.getObjCLifetime())
1038 Comparison.Qualifiers = ParamMoreQualified;
1039 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1040 ArgQuals.getObjCLifetime())
1041 Comparison.Qualifiers = ArgMoreQualified;
1042 }
Douglas Gregor63814022011-01-21 17:29:42 +00001043 RefParamComparisons->push_back(Comparison);
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 // C++0x [temp.deduct.partial]p7:
1047 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001049 // version of P.
1050 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001052 // version of A.
1053 Arg = Arg.getUnqualifiedType();
1054 } else {
1055 // C++0x [temp.deduct.call]p4 bullet 1:
1056 // - If the original P is a reference type, the deduced A (i.e., the type
1057 // referred to by the reference) can be more cv-qualified than the
1058 // transformed A.
1059 if (TDF & TDF_ParamWithReferenceType) {
1060 Qualifiers Quals;
1061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001063 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001064 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Douglas Gregor85f240c2011-01-25 17:19:08 +00001067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1068 // C++0x [temp.deduct.type]p10:
1069 // If P and A are function types that originated from deduction when
1070 // taking the address of a function template (14.8.2.2) or when deducing
1071 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 // Ai are parameters of the top-level parameter-type-list of P and A,
1073 // respectively, Pi is adjusted if it is an rvalue reference to a
1074 // cv-unqualified template parameter and Ai is an lvalue reference, in
1075 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001078 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001079 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Douglas Gregor85f240c2011-01-25 17:19:08 +00001081 if (const RValueReferenceType *ParamRef
1082 = Param->getAs<RValueReferenceType>()) {
1083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1084 !ParamRef->getPointeeType().getQualifiers())
1085 if (Arg->isLValueReferenceType())
1086 Param = ParamRef->getPointeeType();
1087 }
1088 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001091 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001092 // A template type argument T, a template template argument TT or a
1093 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001094 // the following forms:
1095 //
1096 // T
1097 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001099 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001100 // Just skip any attempts to deduce from a placeholder type.
1101 if (Arg->isPlaceholderType())
1102 return Sema::TDK_Success;
1103
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001104 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001105 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregor60454822009-07-22 20:02:25 +00001107 // If the argument type is an array type, move the qualifiers up to the
1108 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001109 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001110 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001111 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001112 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001113 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001114 RecanonicalizeArg = true;
1115 }
1116 }
Mike Stump11289f42009-09-09 15:08:12 +00001117
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001118 // The argument type can not be less qualified than the parameter
1119 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001120 if (!(TDF & TDF_IgnoreQualifiers) &&
1121 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001122 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001123 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001124 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001125 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001126 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001127
1128 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001129 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001130 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001131
Douglas Gregor1d684c22011-04-28 00:56:09 +00001132 // Remove any qualifiers on the parameter from the deduced type.
1133 // We checked the qualifiers for consistency above.
1134 Qualifiers DeducedQs = DeducedType.getQualifiers();
1135 Qualifiers ParamQs = Param.getQualifiers();
1136 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1137 if (ParamQs.hasObjCGCAttr())
1138 DeducedQs.removeObjCGCAttr();
1139 if (ParamQs.hasAddressSpace())
1140 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001141 if (ParamQs.hasObjCLifetime())
1142 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001143
1144 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001145 // If template deduction would produce a lifetime qualifier on a type
1146 // that is not a lifetime type, template argument deduction fails.
1147 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1148 !DeducedType->isDependentType()) {
1149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1150 Info.FirstArg = TemplateArgument(Param);
1151 Info.SecondArg = TemplateArgument(Arg);
1152 return Sema::TDK_Underqualified;
1153 }
1154
1155 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001156 // If template deduction would produce an argument type with lifetime type
1157 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001159 DeducedType->isObjCLifetimeType() &&
1160 !DeducedQs.hasObjCLifetime())
1161 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1162
Douglas Gregor1d684c22011-04-28 00:56:09 +00001163 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1164 DeducedQs);
1165
Douglas Gregord6605db2009-07-22 21:30:48 +00001166 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001167 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001169 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001171 Deduced[Index],
1172 NewDeduced);
1173 if (Result.isNull()) {
1174 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1175 Info.FirstArg = Deduced[Index];
1176 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001180 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001182 }
1183
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001184 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001185 Info.FirstArg = TemplateArgument(ParamIn);
1186 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001187
Douglas Gregorfb322d82011-01-14 05:11:40 +00001188 // If the parameter is an already-substituted template parameter
1189 // pack, do nothing: we don't know which of its arguments to look
1190 // at, so we have to wait until all of the parameter packs in this
1191 // expansion have arguments.
1192 if (isa<SubstTemplateTypeParmPackType>(Param))
1193 return Sema::TDK_Success;
1194
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001195 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001196 CanQualType CanParam = S.Context.getCanonicalType(Param);
1197 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001198 if (!(TDF & TDF_IgnoreQualifiers)) {
1199 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001200 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001201 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001202 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001204 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001205 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001206
1207 // If the parameter type is not dependent, there is nothing to deduce.
1208 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001209 if (!(TDF & TDF_SkipNonDependent)) {
1210 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1211 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1212 Param != Arg;
1213 if (NonDeduced) {
1214 return Sema::TDK_NonDeducedMismatch;
1215 }
1216 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001217 return Sema::TDK_Success;
1218 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001219 } else if (!Param->isDependentType()) {
1220 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1221 ArgUnqualType = CanArg.getUnqualifiedType();
1222 bool Success = (TDF & TDF_InOverloadResolution)?
1223 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1224 ArgUnqualType) :
1225 ParamUnqualType == ArgUnqualType;
1226 if (Success)
1227 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001228 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001229
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001230 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 // Non-canonical types cannot appear here.
1232#define NON_CANONICAL_TYPE(Class, Base) \
1233 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1234#define TYPE(Class, Base)
1235#include "clang/AST/TypeNodes.def"
1236
1237 case Type::TemplateTypeParm:
1238 case Type::SubstTemplateTypeParmPack:
1239 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001240
1241 // These types cannot be dependent, so simply check whether the types are
1242 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001243 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001244 case Type::VariableArray:
1245 case Type::Vector:
1246 case Type::FunctionNoProto:
1247 case Type::Record:
1248 case Type::Enum:
1249 case Type::ObjCObject:
1250 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001251 case Type::ObjCObjectPointer: {
1252 if (TDF & TDF_SkipNonDependent)
1253 return Sema::TDK_Success;
1254
1255 if (TDF & TDF_IgnoreQualifiers) {
1256 Param = Param.getUnqualifiedType();
1257 Arg = Arg.getUnqualifiedType();
1258 }
1259
1260 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1261 }
1262
Douglas Gregor39c02722011-06-15 16:02:29 +00001263 // _Complex T [placeholder extension]
1264 case Type::Complex:
1265 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001266 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001267 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001268 ComplexArg->getElementType(),
1269 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001270
1271 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001272
1273 // _Atomic T [extension]
1274 case Type::Atomic:
1275 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001276 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001277 cast<AtomicType>(Param)->getValueType(),
1278 AtomicArg->getValueType(),
1279 Info, Deduced, TDF);
1280
1281 return Sema::TDK_NonDeducedMismatch;
1282
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001283 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001284 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001285 QualType PointeeType;
1286 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1287 PointeeType = PointerArg->getPointeeType();
1288 } else if (const ObjCObjectPointerType *PointerArg
1289 = Arg->getAs<ObjCObjectPointerType>()) {
1290 PointeeType = PointerArg->getPointeeType();
1291 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001292 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Douglas Gregorfc516c92009-06-26 23:27:24 +00001295 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1297 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001298 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001299 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001302 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001303 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001304 const LValueReferenceType *ReferenceArg =
1305 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001306 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001307 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001309 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001310 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001311 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001313
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001314 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001315 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001316 const RValueReferenceType *ReferenceArg =
1317 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001318 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001319 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1322 cast<RValueReferenceType>(Param)->getPointeeType(),
1323 ReferenceArg->getPointeeType(),
1324 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001328 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001329 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001330 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001331 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001332 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCallf7332682010-08-19 00:20:19 +00001334 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001335 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1336 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1337 IncompleteArrayArg->getElementType(),
1338 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001339 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001340
1341 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001342 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001343 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001344 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001345 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001349 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001350 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001351 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCallf7332682010-08-19 00:20:19 +00001353 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1355 ConstantArrayParm->getElementType(),
1356 ConstantArrayArg->getElementType(),
1357 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 }
1359
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 // type [i]
1361 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001362 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001364 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001365
John McCallf7332682010-08-19 00:20:19 +00001366 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1367
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001368 // Check the element type of the arrays
1369 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001370 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001371 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001372 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1373 DependentArrayParm->getElementType(),
1374 ArrayArg->getElementType(),
1375 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001376 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001378 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001379 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001380 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1381 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001382 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001385 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001386 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001388 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001389 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1390 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001392 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001393 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001394 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001395 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 if (const DependentSizedArrayType *DependentArrayArg
1397 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001398 if (DependentArrayArg->getSizeExpr())
1399 return DeduceNonTypeTemplateArgument(S, NTTP,
1400 DependentArrayArg->getSizeExpr(),
1401 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001403 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001404 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
1407 // type(*)(T)
1408 // T(*)()
1409 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001410 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001411 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001412 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 dyn_cast<FunctionProtoType>(Arg);
1414 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001415 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001416
1417 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001418 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001419
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001421 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001423 != FunctionProtoArg->getRefQualifier() ||
1424 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001425 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001426
Anders Carlsson2128ec72009-06-08 15:19:08 +00001427 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001428 if (Sema::TemplateDeductionResult Result =
1429 DeduceTemplateArgumentsByTypeMatch(
1430 S, TemplateParams, FunctionProtoParam->getReturnType(),
1431 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001432 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Alp Toker9cacbab2014-01-20 20:26:09 +00001434 return DeduceTemplateArguments(
1435 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1436 FunctionProtoParam->getNumParams(),
1437 FunctionProtoArg->param_type_begin(),
1438 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCalle78aac42010-03-10 03:28:59 +00001441 case Type::InjectedClassName: {
1442 // Treat a template's injected-class-name as if the template
1443 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001444 Param = cast<InjectedClassNameType>(Param)
1445 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001446 assert(isa<TemplateSpecializationType>(Param) &&
1447 "injected class name is not a template specialization type");
1448 // fall through
1449 }
1450
Douglas Gregor705c9002009-06-26 20:57:09 +00001451 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001452 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001453 // TT<T>
1454 // TT<i>
1455 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001456 case Type::TemplateSpecialization: {
1457 const TemplateSpecializationType *SpecParam
1458 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Douglas Gregore81f3e72009-07-07 23:09:34 +00001460 // Try to deduce template arguments from the template-id.
1461 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001462 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001463 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Douglas Gregor42909752009-09-30 22:13:51 +00001465 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001466 // C++ [temp.deduct.call]p3b3:
1467 // If P is a class, and P has the form template-id, then A can be a
1468 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001469 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001470 // class pointed to by the deduced A.
1471 //
1472 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001473 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001474 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001475 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1476 // We cannot inspect base classes as part of deduction when the type
1477 // is incomplete, so either instantiate any templates necessary to
1478 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001479 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001480 return Result;
1481
Douglas Gregore81f3e72009-07-07 23:09:34 +00001482 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001483 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001484 // ToVisit is our stack of records that we still need to visit.
1485 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001486 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001487 ToVisit.push_back(RecordT);
1488 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001489 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1490 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 while (!ToVisit.empty()) {
1492 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001493 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001494
Douglas Gregore81f3e72009-07-07 23:09:34 +00001495 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001496 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001497 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001498
Douglas Gregore81f3e72009-07-07 23:09:34 +00001499 // If this is a base class, try to perform template argument
1500 // deduction from it.
1501 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001502 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001503 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001504 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001505 QualType(NextT, 0), BaseInfo,
1506 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Douglas Gregore81f3e72009-07-07 23:09:34 +00001508 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001509 // note that we had some success. Otherwise, ignore any deductions
1510 // from this base class.
1511 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001512 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001513 DeducedOrig.clear();
1514 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001515 Info.Param = BaseInfo.Param;
1516 Info.FirstArg = BaseInfo.FirstArg;
1517 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001518 }
1519 else
1520 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregore81f3e72009-07-07 23:09:34 +00001523 // Visit base classes
1524 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001525 for (const auto &Base : Next->bases()) {
1526 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001527 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001528 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001529 }
1530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregore81f3e72009-07-07 23:09:34 +00001532 if (Successful)
1533 return Sema::TDK_Success;
1534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregore81f3e72009-07-07 23:09:34 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Douglas Gregore81f3e72009-07-07 23:09:34 +00001538 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001539 }
1540
Douglas Gregor637d9982009-06-10 23:47:09 +00001541 // T type::*
1542 // T T::*
1543 // T (type::*)()
1544 // type (T::*)()
1545 // type (type::*)(T)
1546 // type (T::*)(T)
1547 // T (type::*)(T)
1548 // T (T::*)()
1549 // T (T::*)(T)
1550 case Type::MemberPointer: {
1551 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1552 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1553 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001554 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001555
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001556 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001557 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1558 MemPtrParam->getPointeeType(),
1559 MemPtrArg->getPointeeType(),
1560 Info, Deduced,
1561 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001562 return Result;
1563
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001564 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1565 QualType(MemPtrParam->getClass(), 0),
1566 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001567 Info, Deduced,
1568 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001569 }
1570
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001571 // (clang extension)
1572 //
Mike Stump11289f42009-09-09 15:08:12 +00001573 // type(^)(T)
1574 // T(^)()
1575 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001576 case Type::BlockPointer: {
1577 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1578 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Anders Carlssona767eee2009-06-12 16:23:10 +00001580 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001581 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001582
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001583 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1584 BlockPtrParam->getPointeeType(),
1585 BlockPtrArg->getPointeeType(),
1586 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001587 }
1588
Douglas Gregor39c02722011-06-15 16:02:29 +00001589 // (clang extension)
1590 //
1591 // T __attribute__(((ext_vector_type(<integral constant>))))
1592 case Type::ExtVector: {
1593 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1594 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1595 // Make sure that the vectors have the same number of elements.
1596 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1597 return Sema::TDK_NonDeducedMismatch;
1598
1599 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001600 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1601 VectorParam->getElementType(),
1602 VectorArg->getElementType(),
1603 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001604 }
1605
1606 if (const DependentSizedExtVectorType *VectorArg
1607 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1608 // We can't check the number of elements, since the argument has a
1609 // dependent number of elements. This can only occur during partial
1610 // ordering.
1611
1612 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001613 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1614 VectorParam->getElementType(),
1615 VectorArg->getElementType(),
1616 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001617 }
1618
1619 return Sema::TDK_NonDeducedMismatch;
1620 }
1621
1622 // (clang extension)
1623 //
1624 // T __attribute__(((ext_vector_type(N))))
1625 case Type::DependentSizedExtVector: {
1626 const DependentSizedExtVectorType *VectorParam
1627 = cast<DependentSizedExtVectorType>(Param);
1628
1629 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1630 // Perform deduction on the element types.
1631 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001632 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1633 VectorParam->getElementType(),
1634 VectorArg->getElementType(),
1635 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001636 return Result;
1637
1638 // Perform deduction on the vector size, if we can.
1639 NonTypeTemplateParmDecl *NTTP
1640 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1641 if (!NTTP)
1642 return Sema::TDK_Success;
1643
1644 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1645 ArgSize = VectorArg->getNumElements();
1646 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1647 false, Info, Deduced);
1648 }
1649
1650 if (const DependentSizedExtVectorType *VectorArg
1651 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1652 // Perform deduction on the element types.
1653 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001654 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1655 VectorParam->getElementType(),
1656 VectorArg->getElementType(),
1657 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001658 return Result;
1659
1660 // Perform deduction on the vector size, if we can.
1661 NonTypeTemplateParmDecl *NTTP
1662 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1663 if (!NTTP)
1664 return Sema::TDK_Success;
1665
1666 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1667 Info, Deduced);
1668 }
1669
1670 return Sema::TDK_NonDeducedMismatch;
1671 }
1672
Douglas Gregor637d9982009-06-10 23:47:09 +00001673 case Type::TypeOfExpr:
1674 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001675 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001676 case Type::UnresolvedUsing:
1677 case Type::Decltype:
1678 case Type::UnaryTransform:
1679 case Type::Auto:
1680 case Type::DependentTemplateSpecialization:
1681 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001682 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001683 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001684 }
1685
David Blaikiee4d798f2012-01-20 21:50:17 +00001686 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001687}
1688
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001689static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001690DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001691 TemplateParameterList *TemplateParams,
1692 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001693 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001694 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001695 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001696 // If the template argument is a pack expansion, perform template argument
1697 // deduction against the pattern of that expansion. This only occurs during
1698 // partial ordering.
1699 if (Arg.isPackExpansion())
1700 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001702 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001703 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001704 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001705
1706 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001707 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001708 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1709 Param.getAsType(),
1710 Arg.getAsType(),
1711 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001712 Info.FirstArg = Param;
1713 Info.SecondArg = Arg;
1714 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001715
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001716 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001717 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001719 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001720 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001721 Info.FirstArg = Param;
1722 Info.SecondArg = Arg;
1723 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001724
1725 case TemplateArgument::TemplateExpansion:
1726 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001728 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001729 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001730 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001731 return Sema::TDK_Success;
1732
1733 Info.FirstArg = Param;
1734 Info.SecondArg = Arg;
1735 return Sema::TDK_NonDeducedMismatch;
1736
1737 case TemplateArgument::NullPtr:
1738 if (Arg.getKind() == TemplateArgument::NullPtr &&
1739 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001740 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001742 Info.FirstArg = Param;
1743 Info.SecondArg = Arg;
1744 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001746 case TemplateArgument::Integral:
1747 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001748 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001749 return Sema::TDK_Success;
1750
1751 Info.FirstArg = Param;
1752 Info.SecondArg = Arg;
1753 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001754 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001755
1756 if (Arg.getKind() == TemplateArgument::Expression) {
1757 Info.FirstArg = Param;
1758 Info.SecondArg = Arg;
1759 return Sema::TDK_NonDeducedMismatch;
1760 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001762 Info.FirstArg = Param;
1763 Info.SecondArg = Arg;
1764 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001765
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001766 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001767 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001768 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1769 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001770 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001771 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001772 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001773 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001774 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001775 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001776 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001777 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001778 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001779 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001780 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001782 Info.FirstArg = Param;
1783 Info.SecondArg = Arg;
1784 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001785 }
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001788 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001789 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001790 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001791 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
David Blaikiee4d798f2012-01-20 21:50:17 +00001794 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001795}
1796
Douglas Gregor7baabef2010-12-22 18:17:10 +00001797/// \brief Determine whether there is a template argument to be used for
1798/// deduction.
1799///
1800/// This routine "expands" argument packs in-place, overriding its input
1801/// parameters so that \c Args[ArgIdx] will be the available template argument.
1802///
1803/// \returns true if there is another template argument (which will be at
1804/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001806 unsigned &ArgIdx,
1807 unsigned &NumArgs) {
1808 if (ArgIdx == NumArgs)
1809 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregor7baabef2010-12-22 18:17:10 +00001811 const TemplateArgument &Arg = Args[ArgIdx];
1812 if (Arg.getKind() != TemplateArgument::Pack)
1813 return true;
1814
1815 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1816 Args = Arg.pack_begin();
1817 NumArgs = Arg.pack_size();
1818 ArgIdx = 0;
1819 return ArgIdx < NumArgs;
1820}
1821
Douglas Gregord0ad2942010-12-23 01:24:45 +00001822/// \brief Determine whether the given set of template arguments has a pack
1823/// expansion that is not the last template argument.
1824static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1825 unsigned NumArgs) {
1826 unsigned ArgIdx = 0;
1827 while (ArgIdx < NumArgs) {
1828 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001829
Douglas Gregord0ad2942010-12-23 01:24:45 +00001830 // Unwrap argument packs.
1831 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1832 Args = Arg.pack_begin();
1833 NumArgs = Arg.pack_size();
1834 ArgIdx = 0;
1835 continue;
1836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregord0ad2942010-12-23 01:24:45 +00001838 ++ArgIdx;
1839 if (ArgIdx == NumArgs)
1840 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Douglas Gregord0ad2942010-12-23 01:24:45 +00001842 if (Arg.isPackExpansion())
1843 return true;
1844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregord0ad2942010-12-23 01:24:45 +00001846 return false;
1847}
1848
Douglas Gregor7baabef2010-12-22 18:17:10 +00001849static Sema::TemplateDeductionResult
1850DeduceTemplateArguments(Sema &S,
1851 TemplateParameterList *TemplateParams,
1852 const TemplateArgument *Params, unsigned NumParams,
1853 const TemplateArgument *Args, unsigned NumArgs,
1854 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001855 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001856 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001857 // If the template argument list of P contains a pack expansion that is not
1858 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001859 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001860 if (hasPackExpansionBeforeEnd(Params, NumParams))
1861 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001863 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 // If P has a form that contains <T> or <i>, then each argument Pi of the
1865 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001866 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001867 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 ++ParamIdx) {
1870 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001871 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Douglas Gregor7baabef2010-12-22 18:17:10 +00001873 // Check whether we have enough arguments.
1874 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001875 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001877 if (Args[ArgIdx].isPackExpansion()) {
1878 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1879 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001880 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001883 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001884 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001885 = DeduceTemplateArguments(S, TemplateParams,
1886 Params[ParamIdx], Args[ArgIdx],
1887 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888 return Result;
1889
Douglas Gregor7baabef2010-12-22 18:17:10 +00001890 // Move to the next argument.
1891 ++ArgIdx;
1892 continue;
1893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001895 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001897 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898 // If Pi is a pack expansion, then the pattern of Pi is compared with
1899 // each remaining argument in the template argument list of A. Each
1900 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001901 // template parameter packs expanded by Pi.
1902 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001904 // FIXME: If there are no remaining arguments, we can bail out early
1905 // and set any deduced parameter packs to an empty argument pack.
1906 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Richard Smith0a80d572014-05-29 01:12:14 +00001908 // Prepare to deduce the packs within the pattern.
1909 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001910
1911 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001914 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001915 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001918 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1921 Info, Deduced))
1922 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Richard Smith0a80d572014-05-29 01:12:14 +00001924 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // Build argument packs for each of the parameter packs expanded by this
1928 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001929 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor7baabef2010-12-22 18:17:10 +00001933 return Sema::TDK_Success;
1934}
1935
Mike Stump11289f42009-09-09 15:08:12 +00001936static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001937DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001938 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001939 const TemplateArgumentList &ParamList,
1940 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001941 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001942 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001944 ParamList.data(), ParamList.size(),
1945 ArgList.data(), ArgList.size(),
1946 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001947}
1948
Douglas Gregor705c9002009-06-26 20:57:09 +00001949/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001950static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001951 const TemplateArgument &X,
1952 const TemplateArgument &Y) {
1953 if (X.getKind() != Y.getKind())
1954 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregor705c9002009-06-26 20:57:09 +00001956 switch (X.getKind()) {
1957 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001958 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor705c9002009-06-26 20:57:09 +00001960 case TemplateArgument::Type:
1961 return Context.getCanonicalType(X.getAsType()) ==
1962 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor705c9002009-06-26 20:57:09 +00001964 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001965 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001966
1967 case TemplateArgument::NullPtr:
1968 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001969
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001970 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001971 case TemplateArgument::TemplateExpansion:
1972 return Context.getCanonicalTemplateName(
1973 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1974 Context.getCanonicalTemplateName(
1975 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Douglas Gregor705c9002009-06-26 20:57:09 +00001977 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001978 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001980 case TemplateArgument::Expression: {
1981 llvm::FoldingSetNodeID XID, YID;
1982 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001984 return XID == YID;
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Douglas Gregor705c9002009-06-26 20:57:09 +00001987 case TemplateArgument::Pack:
1988 if (X.pack_size() != Y.pack_size())
1989 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001990
1991 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1992 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001993 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001994 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001995 if (!isSameTemplateArg(Context, *XP, *YP))
1996 return false;
1997
1998 return true;
1999 }
2000
David Blaikiee4d798f2012-01-20 21:50:17 +00002001 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002002}
2003
Douglas Gregorca4686d2011-01-04 23:35:54 +00002004/// \brief Allocate a TemplateArgumentLoc where all locations have
2005/// been initialized to the given location.
2006///
2007/// \param S The semantic analysis object.
2008///
James Dennett634962f2012-06-14 21:40:34 +00002009/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002010/// location information for.
2011///
2012/// \param NTTPType For a declaration template argument, the type of
2013/// the non-type template parameter that corresponds to this template
2014/// argument.
2015///
2016/// \param Loc The source location to use for the resulting template
2017/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00002019getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002021 QualType NTTPType,
2022 SourceLocation Loc) {
2023 switch (Arg.getKind()) {
2024 case TemplateArgument::Null:
2025 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026
Douglas Gregorca4686d2011-01-04 23:35:54 +00002027 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002029 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
Douglas Gregorca4686d2011-01-04 23:35:54 +00002031 case TemplateArgument::Declaration: {
2032 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002033 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002034 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002035 return TemplateArgumentLoc(TemplateArgument(E), E);
2036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Eli Friedmanb826a002012-09-26 02:36:12 +00002038 case TemplateArgument::NullPtr: {
2039 Expr *E
2040 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002041 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002042 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2043 E);
2044 }
2045
Douglas Gregorca4686d2011-01-04 23:35:54 +00002046 case TemplateArgument::Integral: {
2047 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002048 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049 return TemplateArgumentLoc(TemplateArgument(E), E);
2050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051
Douglas Gregor9d802122011-03-02 17:09:35 +00002052 case TemplateArgument::Template:
2053 case TemplateArgument::TemplateExpansion: {
2054 NestedNameSpecifierLocBuilder Builder;
2055 TemplateName Template = Arg.getAsTemplate();
2056 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2057 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002058 else if (QualifiedTemplateName *QTN =
2059 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002060 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2061
2062 if (Arg.getKind() == TemplateArgument::Template)
2063 return TemplateArgumentLoc(Arg,
2064 Builder.getWithLocInContext(S.Context),
2065 Loc);
2066
2067
2068 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2069 Loc, Loc);
2070 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002071
Douglas Gregorca4686d2011-01-04 23:35:54 +00002072 case TemplateArgument::Expression:
2073 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075 case TemplateArgument::Pack:
2076 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
David Blaikiee4d798f2012-01-20 21:50:17 +00002079 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080}
2081
2082
2083/// \brief Convert the given deduced template argument and add it to the set of
2084/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002085static bool
2086ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2087 DeducedTemplateArgument Arg,
2088 NamedDecl *Template,
2089 QualType NTTPType,
2090 unsigned ArgumentPackIndex,
2091 TemplateDeductionInfo &Info,
2092 bool InFunctionTemplate,
2093 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002094 if (Arg.getKind() == TemplateArgument::Pack) {
2095 // This is a template argument pack, so check each of its arguments against
2096 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002098 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002099 // When converting the deduced template argument, append it to the
2100 // general output list. We need to do this so that the template argument
2101 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002102 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002103 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002105 NTTPType, PackedArgsBuilder.size(),
2106 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002107 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Douglas Gregor51bc5712011-01-05 20:52:18 +00002109 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002110 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregorca4686d2011-01-04 23:35:54 +00002113 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002115 PackedArgsBuilder.data(),
2116 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 return false;
2118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 // Convert the deduced template argument into a template
2121 // argument that we can check, almost as if the user had written
2122 // the template argument explicitly.
2123 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2124 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125
Douglas Gregorca4686d2011-01-04 23:35:54 +00002126 // Check the template argument, converting it as necessary.
2127 return S.CheckTemplateArgument(Param, ArgLoc,
2128 Template,
2129 Template->getLocation(),
2130 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002131 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002132 Output,
2133 InFunctionTemplate
2134 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002136 : Sema::CTAK_Deduced)
2137 : Sema::CTAK_Specified);
2138}
2139
Douglas Gregor684268d2010-04-29 06:21:43 +00002140/// Complete template argument deduction for a class template partial
2141/// specialization.
2142static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002144 ClassTemplatePartialSpecializationDecl *Partial,
2145 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002146 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002147 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002148 // Unevaluated SFINAE context.
2149 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002150 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor684268d2010-04-29 06:21:43 +00002152 Sema::ContextRAII SavedContext(S, Partial);
2153
2154 // C++ [temp.deduct.type]p2:
2155 // [...] or if any template argument remains neither deduced nor
2156 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002157 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002158 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2159 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002160 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002161 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002162 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002163 return Sema::TDK_Incomplete;
2164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Douglas Gregorca4686d2011-01-04 23:35:54 +00002166 // We have deduced this argument, so it still needs to be
2167 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregorca4686d2011-01-04 23:35:54 +00002169 // First, for a non-type template parameter type that is
2170 // initialized by a declaration, we need the type of the
2171 // corresponding non-type template parameter.
2172 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002174 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002175 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002176 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002178 Builder.data(), Builder.size());
2179 NTTPType = S.SubstType(NTTPType,
2180 MultiLevelTemplateArgumentList(TemplateArgs),
2181 NTTP->getLocation(),
2182 NTTP->getDeclName());
2183 if (NTTPType.isNull()) {
2184 Info.Param = makeTemplateParameter(Param);
2185 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2187 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002188 Builder.size()));
2189 return Sema::TDK_SubstitutionFailure;
2190 }
2191 }
2192 }
2193
Douglas Gregorca4686d2011-01-04 23:35:54 +00002194 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002195 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002196 Builder)) {
2197 Info.Param = makeTemplateParameter(Param);
2198 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2200 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002201 return Sema::TDK_SubstitutionFailure;
2202 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Douglas Gregor684268d2010-04-29 06:21:43 +00002205 // Form the template argument list from the deduced template arguments.
2206 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002208 Builder.size());
2209
Douglas Gregor684268d2010-04-29 06:21:43 +00002210 Info.reset(DeducedArgumentList);
2211
2212 // Substitute the deduced template arguments into the template
2213 // arguments of the class template partial specialization, and
2214 // verify that the instantiated template arguments are both valid
2215 // and are equivalent to the template arguments originally provided
2216 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002217 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002218 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002219 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002220 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002221 const TemplateArgumentLoc *PartialTemplateArgs
2222 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002223
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002224 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2225 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002226
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002227 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002228 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2229 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2230 if (ParamIdx >= Partial->getTemplateParameters()->size())
2231 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2232
2233 Decl *Param
2234 = const_cast<NamedDecl *>(
2235 Partial->getTemplateParameters()->getParam(ParamIdx));
2236 Info.Param = makeTemplateParameter(Param);
2237 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2238 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002239 }
2240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002241 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002242 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002243 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002244 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002245
Douglas Gregorca4686d2011-01-04 23:35:54 +00002246 TemplateParameterList *TemplateParams
2247 = ClassTemplate->getTemplateParameters();
2248 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002249 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002250 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002251 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002252 Info.FirstArg = TemplateArgs[I];
2253 Info.SecondArg = InstArg;
2254 return Sema::TDK_NonDeducedMismatch;
2255 }
2256 }
2257
2258 if (Trap.hasErrorOccurred())
2259 return Sema::TDK_SubstitutionFailure;
2260
2261 return Sema::TDK_Success;
2262}
2263
Douglas Gregor170bc422009-06-12 22:31:52 +00002264/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002265/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002266/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002267Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002268Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002269 const TemplateArgumentList &TemplateArgs,
2270 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002271 if (Partial->isInvalidDecl())
2272 return TDK_Invalid;
2273
Douglas Gregor170bc422009-06-12 22:31:52 +00002274 // C++ [temp.class.spec.match]p2:
2275 // A partial specialization matches a given actual template
2276 // argument list if the template arguments of the partial
2277 // specialization can be deduced from the actual template argument
2278 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002279
2280 // Unevaluated SFINAE context.
2281 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002282 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002283
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002284 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002285 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002286 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002287 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002288 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002289 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002290 TemplateArgs, Info, Deduced))
2291 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002292
Richard Smith80934652012-07-16 01:09:10 +00002293 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002294 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2295 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002296 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002297 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002298
Douglas Gregore1416332009-06-14 08:02:22 +00002299 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002300 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301
2302 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002303 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002304}
Douglas Gregor91772d12009-06-13 00:26:55 +00002305
Larisse Voufo39a1e502013-08-06 01:03:05 +00002306/// Complete template argument deduction for a variable template partial
2307/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002308/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2309/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2310/// VarTemplate(Partial)SpecializationDecl with a new data
2311/// structure Template(Partial)SpecializationDecl, and
2312/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002313static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2314 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2315 const TemplateArgumentList &TemplateArgs,
2316 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2317 TemplateDeductionInfo &Info) {
2318 // Unevaluated SFINAE context.
2319 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2320 Sema::SFINAETrap Trap(S);
2321
2322 // C++ [temp.deduct.type]p2:
2323 // [...] or if any template argument remains neither deduced nor
2324 // explicitly specified, template argument deduction fails.
2325 SmallVector<TemplateArgument, 4> Builder;
2326 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2327 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2328 NamedDecl *Param = PartialParams->getParam(I);
2329 if (Deduced[I].isNull()) {
2330 Info.Param = makeTemplateParameter(Param);
2331 return Sema::TDK_Incomplete;
2332 }
2333
2334 // We have deduced this argument, so it still needs to be
2335 // checked and converted.
2336
2337 // First, for a non-type template parameter type that is
2338 // initialized by a declaration, we need the type of the
2339 // corresponding non-type template parameter.
2340 QualType NTTPType;
2341 if (NonTypeTemplateParmDecl *NTTP =
2342 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2343 NTTPType = NTTP->getType();
2344 if (NTTPType->isDependentType()) {
2345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2346 Builder.data(), Builder.size());
2347 NTTPType =
2348 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2349 NTTP->getLocation(), NTTP->getDeclName());
2350 if (NTTPType.isNull()) {
2351 Info.Param = makeTemplateParameter(Param);
2352 // FIXME: These template arguments are temporary. Free them!
2353 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2354 Builder.size()));
2355 return Sema::TDK_SubstitutionFailure;
2356 }
2357 }
2358 }
2359
2360 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2361 0, Info, false, Builder)) {
2362 Info.Param = makeTemplateParameter(Param);
2363 // FIXME: These template arguments are temporary. Free them!
2364 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2365 Builder.size()));
2366 return Sema::TDK_SubstitutionFailure;
2367 }
2368 }
2369
2370 // Form the template argument list from the deduced template arguments.
2371 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2372 S.Context, Builder.data(), Builder.size());
2373
2374 Info.reset(DeducedArgumentList);
2375
2376 // Substitute the deduced template arguments into the template
2377 // arguments of the class template partial specialization, and
2378 // verify that the instantiated template arguments are both valid
2379 // and are equivalent to the template arguments originally provided
2380 // to the class template.
2381 LocalInstantiationScope InstScope(S);
2382 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002383 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2384 = Partial->getTemplateArgsAsWritten();
2385 const TemplateArgumentLoc *PartialTemplateArgs
2386 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002387
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002388 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2389 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002390
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002391 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002392 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2393 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2394 if (ParamIdx >= Partial->getTemplateParameters()->size())
2395 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2396
2397 Decl *Param = const_cast<NamedDecl *>(
2398 Partial->getTemplateParameters()->getParam(ParamIdx));
2399 Info.Param = makeTemplateParameter(Param);
2400 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2401 return Sema::TDK_SubstitutionFailure;
2402 }
2403 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2404 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2405 false, ConvertedInstArgs))
2406 return Sema::TDK_SubstitutionFailure;
2407
2408 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2409 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2410 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2411 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2412 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2413 Info.FirstArg = TemplateArgs[I];
2414 Info.SecondArg = InstArg;
2415 return Sema::TDK_NonDeducedMismatch;
2416 }
2417 }
2418
2419 if (Trap.hasErrorOccurred())
2420 return Sema::TDK_SubstitutionFailure;
2421
2422 return Sema::TDK_Success;
2423}
2424
2425/// \brief Perform template argument deduction to determine whether
2426/// the given template arguments match the given variable template
2427/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002428/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2429/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2430/// VarTemplate(Partial)SpecializationDecl with a new data
2431/// structure Template(Partial)SpecializationDecl, and
2432/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002433Sema::TemplateDeductionResult
2434Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2435 const TemplateArgumentList &TemplateArgs,
2436 TemplateDeductionInfo &Info) {
2437 if (Partial->isInvalidDecl())
2438 return TDK_Invalid;
2439
2440 // C++ [temp.class.spec.match]p2:
2441 // A partial specialization matches a given actual template
2442 // argument list if the template arguments of the partial
2443 // specialization can be deduced from the actual template argument
2444 // list (14.8.2).
2445
2446 // Unevaluated SFINAE context.
2447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2448 SFINAETrap Trap(*this);
2449
2450 SmallVector<DeducedTemplateArgument, 4> Deduced;
2451 Deduced.resize(Partial->getTemplateParameters()->size());
2452 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2453 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2454 TemplateArgs, Info, Deduced))
2455 return Result;
2456
2457 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002458 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2459 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002460 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002461 return TDK_InstantiationDepth;
2462
2463 if (Trap.hasErrorOccurred())
2464 return Sema::TDK_SubstitutionFailure;
2465
2466 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2467 Deduced, Info);
2468}
2469
Douglas Gregorfc516c92009-06-26 23:27:24 +00002470/// \brief Determine whether the given type T is a simple-template-id type.
2471static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002472 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002473 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002474 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Douglas Gregorfc516c92009-06-26 23:27:24 +00002476 return false;
2477}
Douglas Gregor9b146582009-07-08 20:55:45 +00002478
2479/// \brief Substitute the explicitly-provided template arguments into the
2480/// given function template according to C++ [temp.arg.explicit].
2481///
2482/// \param FunctionTemplate the function template into which the explicit
2483/// template arguments will be substituted.
2484///
James Dennett634962f2012-06-14 21:40:34 +00002485/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002486/// arguments.
2487///
Mike Stump11289f42009-09-09 15:08:12 +00002488/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002489/// with the converted and checked explicit template arguments.
2490///
Mike Stump11289f42009-09-09 15:08:12 +00002491/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002492/// parameters.
2493///
2494/// \param FunctionType if non-NULL, the result type of the function template
2495/// will also be instantiated and the pointed-to value will be updated with
2496/// the instantiated function type.
2497///
2498/// \param Info if substitution fails for any reason, this object will be
2499/// populated with more information about the failure.
2500///
2501/// \returns TDK_Success if substitution was successful, or some failure
2502/// condition.
2503Sema::TemplateDeductionResult
2504Sema::SubstituteExplicitTemplateArguments(
2505 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002506 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002507 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2508 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002509 QualType *FunctionType,
2510 TemplateDeductionInfo &Info) {
2511 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2512 TemplateParameterList *TemplateParams
2513 = FunctionTemplate->getTemplateParameters();
2514
John McCall6b51f282009-11-23 01:53:49 +00002515 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002516 // No arguments to substitute; just copy over the parameter types and
2517 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002518 for (auto P : Function->params())
2519 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregor9b146582009-07-08 20:55:45 +00002521 if (FunctionType)
2522 *FunctionType = Function->getType();
2523 return TDK_Success;
2524 }
Mike Stump11289f42009-09-09 15:08:12 +00002525
Eli Friedman77dcc722012-02-08 03:07:05 +00002526 // Unevaluated SFINAE context.
2527 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002528 SFINAETrap Trap(*this);
2529
Douglas Gregor9b146582009-07-08 20:55:45 +00002530 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002531 // Template arguments that are present shall be specified in the
2532 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002533 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002534 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002536
2537 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002538 // explicitly-specified template arguments against this function template,
2539 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002540 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002541 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2542 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002543 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2544 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002545 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002546 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Douglas Gregor9b146582009-07-08 20:55:45 +00002548 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002549 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002550 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002551 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002552 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002553 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002554 if (Index >= TemplateParams->size())
2555 Index = TemplateParams->size() - 1;
2556 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002557 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor9b146582009-07-08 20:55:45 +00002560 // Form the template argument list from the explicitly-specified
2561 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002562 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002563 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002564 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
John McCall036855a2010-10-12 19:40:14 +00002566 // Template argument deduction and the final substitution should be
2567 // done in the context of the templated declaration. Explicit
2568 // argument substitution, on the other hand, needs to happen in the
2569 // calling context.
2570 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002572 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002573 // note that the template argument pack is partially substituted and record
2574 // the explicit template arguments. They'll be used as part of deduction
2575 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002576 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2577 const TemplateArgument &Arg = Builder[I];
2578 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002579 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002581 Arg.pack_begin(),
2582 Arg.pack_size());
2583 break;
2584 }
2585 }
2586
Richard Smith5e580292012-02-10 09:58:53 +00002587 const FunctionProtoType *Proto
2588 = Function->getType()->getAs<FunctionProtoType>();
2589 assert(Proto && "Function template does not have a prototype?");
2590
Richard Smith70b13042015-01-09 01:19:56 +00002591 // Isolate our substituted parameters from our caller.
2592 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
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,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002787 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2788 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002789 TemplateParameterList *TemplateParams
2790 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002791
Eli Friedman77dcc722012-02-08 03:07:05 +00002792 // Unevaluated SFINAE context.
2793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002794 SFINAETrap Trap(*this);
2795
Douglas Gregor9b146582009-07-08 20:55:45 +00002796 // Enter a new template instantiation context while we instantiate the
2797 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002798 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002799 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2800 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002801 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2802 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002803 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002804 return TDK_InstantiationDepth;
2805
John McCalle23b8712010-04-29 01:18:58 +00002806 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002807
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002808 // C++ [temp.deduct.type]p2:
2809 // [...] or if any template argument remains neither deduced nor
2810 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002811 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002812 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2813 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002815 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002816 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002817 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002819 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002820 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002821 // We may have had explicitly-specified template arguments for a
2822 // template parameter pack (that may or may not have been extended
2823 // via additional deduced arguments).
2824 if (Param->isParameterPack() && CurrentInstantiationScope) {
2825 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2826 Param) {
2827 // Forget the partially-substituted pack; its substitution is now
2828 // complete.
2829 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2830 }
2831 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002832 continue;
2833 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002834 // We have deduced this argument, so it still needs to be
2835 // checked and converted.
2836
2837 // First, for a non-type template parameter type that is
2838 // initialized by a declaration, we need the type of the
2839 // corresponding non-type template parameter.
2840 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841 if (NonTypeTemplateParmDecl *NTTP
2842 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002843 NTTPType = NTTP->getType();
2844 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002846 Builder.data(), Builder.size());
2847 NTTPType = SubstType(NTTPType,
2848 MultiLevelTemplateArgumentList(TemplateArgs),
2849 NTTP->getLocation(),
2850 NTTP->getDeclName());
2851 if (NTTPType.isNull()) {
2852 Info.Param = makeTemplateParameter(Param);
2853 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854 Info.reset(TemplateArgumentList::CreateCopy(Context,
2855 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002856 Builder.size()));
2857 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002858 }
2859 }
2860 }
2861
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002862 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002863 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002864 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002865 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002866 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2868 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002869 return TDK_SubstitutionFailure;
2870 }
2871
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002872 continue;
2873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002875 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002876 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002877 // be deduced to an empty sequence of template arguments.
2878 // FIXME: Where did the word "trailing" come from?
2879 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002880 // We may have had explicitly-specified template arguments for this
2881 // template parameter pack. If so, our empty deduction extends the
2882 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2883 const TemplateArgument *ExplicitArgs;
2884 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002885 if (CurrentInstantiationScope &&
2886 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002887 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002888 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002889 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890
Douglas Gregorcaddba92013-01-18 22:27:09 +00002891 // Forget the partially-substituted pack; it's substitution is now
2892 // complete.
2893 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2894 } else {
2895 Builder.push_back(TemplateArgument::getEmptyPack());
2896 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002897 continue;
2898 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002899
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002901 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002902 TemplateArgumentLoc DefArg
2903 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2904 FunctionTemplate->getLocation(),
2905 FunctionTemplate->getSourceRange().getEnd(),
2906 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002907 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002908
2909 // If there was no default argument, deduction is incomplete.
2910 if (DefArg.getArgument().isNull()) {
2911 Info.Param = makeTemplateParameter(
2912 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002913 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2914 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002915 if (PartialOverloading) break;
2916
Richard Smithc87b9382013-07-04 01:01:24 +00002917 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002920 // Check whether we can actually use the default argument.
2921 if (CheckTemplateArgument(Param, DefArg,
2922 FunctionTemplate,
2923 FunctionTemplate->getLocation(),
2924 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002925 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002926 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002927 Info.Param = makeTemplateParameter(
2928 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002929 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002931 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002932 return TDK_SubstitutionFailure;
2933 }
2934
2935 // If we get here, we successfully used the default template argument.
2936 }
2937
2938 // Form the template argument list from the deduced template arguments.
2939 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002940 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002941 Info.reset(DeducedArgumentList);
2942
Mike Stump11289f42009-09-09 15:08:12 +00002943 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002944 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002945 DeclContext *Owner = FunctionTemplate->getDeclContext();
2946 if (FunctionTemplate->getFriendObjectKind())
2947 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002948 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002949 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002950 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002951 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002952 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002955 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956
Mike Stump11289f42009-09-09 15:08:12 +00002957 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002958 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002959 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2960 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002961 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002962
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002963 // There may have been an error that did not prevent us from constructing a
2964 // declaration. Mark the declaration invalid and return with a substitution
2965 // failure.
2966 if (Trap.hasErrorOccurred()) {
2967 Specialization->setInvalidDecl(true);
2968 return TDK_SubstitutionFailure;
2969 }
2970
Douglas Gregore65aacb2011-06-16 16:50:48 +00002971 if (OriginalCallArgs) {
2972 // C++ [temp.deduct.call]p4:
2973 // In general, the deduction process attempts to find template argument
2974 // values that will make the deduced A identical to A (after the type A
2975 // is transformed as described above). [...]
2976 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2977 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002978 unsigned ParamIdx = OriginalArg.ArgIdx;
2979
2980 if (ParamIdx >= Specialization->getNumParams())
2981 continue;
2982
2983 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002984 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2985 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002986 }
2987 }
2988
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002989 // If we suppressed any diagnostics while performing template argument
2990 // deduction, and if we haven't already instantiated this declaration,
2991 // keep track of these diagnostics. They'll be emitted if this specialization
2992 // is actually used.
2993 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002994 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002995 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2996 if (Pos == SuppressedDiagnostics.end())
2997 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2998 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003000
Mike Stump11289f42009-09-09 15:08:12 +00003001 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003002}
3003
John McCall8d08b9b2010-08-27 09:08:28 +00003004/// Gets the type of a function for template-argument-deducton
3005/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003006static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003007 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003008 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003009 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003010 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003011 return QualType();
3012
John McCallc1f69982010-02-02 02:21:27 +00003013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003014 if (Method->isInstance()) {
3015 // An instance method that's referenced in a form that doesn't
3016 // look like a member pointer is just invalid.
3017 if (!R.HasFormOfMemberPointer) return QualType();
3018
Richard Smith2a7d4812013-05-04 07:00:32 +00003019 return S.Context.getMemberPointerType(Fn->getType(),
3020 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003021 }
3022
3023 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003024 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003025}
3026
3027/// Apply the deduction rules for overload sets.
3028///
3029/// \return the null type if this argument should be treated as an
3030/// undeduced context
3031static QualType
3032ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003033 Expr *Arg, QualType ParamType,
3034 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003035
John McCall8d08b9b2010-08-27 09:08:28 +00003036 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003037
John McCall8d08b9b2010-08-27 09:08:28 +00003038 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003039
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003040 // C++0x [temp.deduct.call]p4
3041 unsigned TDF = 0;
3042 if (ParamWasReference)
3043 TDF |= TDF_ParamWithReferenceType;
3044 if (R.IsAddressOfOperand)
3045 TDF |= TDF_IgnoreQualifiers;
3046
John McCallc1f69982010-02-02 02:21:27 +00003047 // C++0x [temp.deduct.call]p6:
3048 // When P is a function type, pointer to function type, or pointer
3049 // to member function type:
3050
3051 if (!ParamType->isFunctionType() &&
3052 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003053 !ParamType->isMemberFunctionPointerType()) {
3054 if (Ovl->hasExplicitTemplateArgs()) {
3055 // But we can still look for an explicit specialization.
3056 if (FunctionDecl *ExplicitSpec
3057 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003058 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003059 }
John McCallc1f69982010-02-02 02:21:27 +00003060
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003061 return QualType();
3062 }
3063
3064 // Gather the explicit template arguments, if any.
3065 TemplateArgumentListInfo ExplicitTemplateArgs;
3066 if (Ovl->hasExplicitTemplateArgs())
3067 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003068 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003069 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3070 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003071 NamedDecl *D = (*I)->getUnderlyingDecl();
3072
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003073 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3074 // - If the argument is an overload set containing one or more
3075 // function templates, the parameter is treated as a
3076 // non-deduced context.
3077 if (!Ovl->hasExplicitTemplateArgs())
3078 return QualType();
3079
3080 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003081 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003082 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003083 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3084 Specialization, Info))
3085 continue;
3086
3087 D = Specialization;
3088 }
John McCallc1f69982010-02-02 02:21:27 +00003089
3090 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003091 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003092 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003093
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003094 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003096 ArgType->isFunctionType())
3097 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098
John McCallc1f69982010-02-02 02:21:27 +00003099 // - If the argument is an overload set (not containing function
3100 // templates), trial argument deduction is attempted using each
3101 // of the members of the set. If deduction succeeds for only one
3102 // of the overload set members, that member is used as the
3103 // argument value for the deduction. If deduction succeeds for
3104 // more than one member of the overload set the parameter is
3105 // treated as a non-deduced context.
3106
3107 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3108 // Type deduction is done independently for each P/A pair, and
3109 // the deduced template argument values are then combined.
3110 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003111 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003112 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003113 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003114 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003115 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3116 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003117 if (Result) continue;
3118 if (!Match.isNull()) return QualType();
3119 Match = ArgType;
3120 }
3121
3122 return Match;
3123}
3124
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003125/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003126/// described in C++ [temp.deduct.call].
3127///
3128/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003129/// argument deduction based on this P/A pair because the argument is an
3130/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003131static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3132 TemplateParameterList *TemplateParams,
3133 QualType &ParamType,
3134 QualType &ArgType,
3135 Expr *Arg,
3136 unsigned &TDF) {
3137 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003138 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003139 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003140 if (ParamType.hasQualifiers())
3141 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003142
3143 // [...] If P is a reference type, the type referred to by P is
3144 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003145 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003146 if (ParamRefType)
3147 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003148
Nathan Sidwell96090022015-01-16 15:20:14 +00003149 // Overload sets usually make this parameter an undeduced context,
3150 // but there are sometimes special circumstances. Typically
3151 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003152 if (ArgType == S.Context.OverloadTy) {
3153 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3154 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003155 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003156 if (ArgType.isNull())
3157 return true;
3158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003161 // If the argument has incomplete array type, try to complete its type.
3162 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
3163 ArgType = Arg->getType();
3164
Douglas Gregor7825bf32011-01-06 22:09:01 +00003165 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003166 // If P is an rvalue reference to a cv-unqualified template
3167 // parameter and the argument is an lvalue, the type "lvalue
3168 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003169 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003170 !ParamType.getQualifiers() &&
3171 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 Arg->isLValue())
3173 ArgType = S.Context.getLValueReferenceType(ArgType);
3174 } else {
3175 // C++ [temp.deduct.call]p2:
3176 // If P is not a reference type:
3177 // - If A is an array type, the pointer type produced by the
3178 // array-to-pointer standard conversion (4.2) is used in place of
3179 // A for type deduction; otherwise,
3180 if (ArgType->isArrayType())
3181 ArgType = S.Context.getArrayDecayedType(ArgType);
3182 // - If A is a function type, the pointer type produced by the
3183 // function-to-pointer standard conversion (4.3) is used in place
3184 // of A for type deduction; otherwise,
3185 else if (ArgType->isFunctionType())
3186 ArgType = S.Context.getPointerType(ArgType);
3187 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003188 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003189 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003190 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003191 }
3192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor7825bf32011-01-06 22:09:01 +00003194 // C++0x [temp.deduct.call]p4:
3195 // In general, the deduction process attempts to find template argument
3196 // values that will make the deduced A identical to A (after the type A
3197 // is transformed as described above). [...]
3198 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Douglas Gregor7825bf32011-01-06 22:09:01 +00003200 // - If the original P is a reference type, the deduced A (i.e., the
3201 // type referred to by the reference) can be more cv-qualified than
3202 // the transformed A.
3203 if (ParamRefType)
3204 TDF |= TDF_ParamWithReferenceType;
3205 // - The transformed A can be another pointer or pointer to member
3206 // type that can be converted to the deduced A via a qualification
3207 // conversion (4.4).
3208 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3209 ArgType->isObjCObjectPointerType())
3210 TDF |= TDF_IgnoreQualifiers;
3211 // - If P is a class and P has the form simple-template-id, then the
3212 // transformed A can be a derived class of the deduced A. Likewise,
3213 // if P is a pointer to a class of the form simple-template-id, the
3214 // transformed A can be a pointer to a derived class pointed to by
3215 // the deduced A.
3216 if (isSimpleTemplateIdType(ParamType) ||
3217 (isa<PointerType>(ParamType) &&
3218 isSimpleTemplateIdType(
3219 ParamType->getAs<PointerType>()->getPointeeType())))
3220 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221
Douglas Gregor7825bf32011-01-06 22:09:01 +00003222 return false;
3223}
3224
Nico Weberc153d242014-07-28 00:02:09 +00003225static bool
3226hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3227 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003228
Sebastian Redl19181662012-03-15 21:40:51 +00003229/// \brief Perform template argument deduction by matching a parameter type
3230/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003231/// an initializer list that was originally matched against a parameter
3232/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003233static Sema::TemplateDeductionResult
3234DeduceTemplateArgumentByListElement(Sema &S,
3235 TemplateParameterList *TemplateParams,
3236 QualType ParamType, Expr *Arg,
3237 TemplateDeductionInfo &Info,
3238 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3239 unsigned TDF) {
3240 // Handle the case where an init list contains another init list as the
3241 // element.
3242 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3243 QualType X;
3244 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3245 return Sema::TDK_Success; // Just ignore this expression.
3246
3247 // Recurse down into the init list.
3248 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3249 if (Sema::TemplateDeductionResult Result =
3250 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3251 ILE->getInit(i),
3252 Info, Deduced, TDF))
3253 return Result;
3254 }
3255 return Sema::TDK_Success;
3256 }
3257
3258 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003259 QualType ArgType = Arg->getType();
3260 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003261 ArgType, Arg, TDF)) {
3262 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003263 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003264 }
Sebastian Redl19181662012-03-15 21:40:51 +00003265 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003266 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003267}
3268
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003269/// \brief Perform template argument deduction from a function call
3270/// (C++ [temp.deduct.call]).
3271///
3272/// \param FunctionTemplate the function template for which we are performing
3273/// template argument deduction.
3274///
James Dennett18348b62012-06-22 08:52:37 +00003275/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003276/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003277///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003278/// \param Args the function call arguments
3279///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003280/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003281/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003282/// template argument deduction.
3283///
3284/// \param Info the argument will be updated to provide additional information
3285/// about template argument deduction.
3286///
3287/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003288Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3289 FunctionTemplateDecl *FunctionTemplate,
3290 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003291 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3292 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003293 if (FunctionTemplate->isInvalidDecl())
3294 return TDK_Invalid;
3295
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003296 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003297 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003298
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003299 // C++ [temp.deduct.call]p1:
3300 // Template argument deduction is done by comparing each function template
3301 // parameter type (call it P) with the type of the corresponding argument
3302 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003303 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003304 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003305 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003306 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003307 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003308 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003309 if (Proto->isTemplateVariadic())
3310 /* Do nothing */;
3311 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003312 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003315 }
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregor89026b52009-06-30 23:57:56 +00003317 // The types of the parameters from which we will perform template argument
3318 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003319 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003320 TemplateParameterList *TemplateParams
3321 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003322 SmallVector<DeducedTemplateArgument, 4> Deduced;
3323 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003324 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003325 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003326 TemplateDeductionResult Result =
3327 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003328 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003329 Deduced,
3330 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003331 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003332 Info);
3333 if (Result)
3334 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003335
3336 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003337 } else {
3338 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003339 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003340 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3341 }
Mike Stump11289f42009-09-09 15:08:12 +00003342
Douglas Gregor89026b52009-06-30 23:57:56 +00003343 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003344 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003345 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003346 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003347 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3348 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003349 QualType OrigParamType = ParamTypes[ParamIdx];
3350 QualType ParamType = OrigParamType;
3351
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003353 = dyn_cast<PackExpansionType>(ParamType);
3354 if (!ParamExpansion) {
3355 // Simple case: matching a function parameter to a function argument.
3356 if (ArgIdx >= CheckArgs)
3357 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358
Douglas Gregor7825bf32011-01-06 22:09:01 +00003359 Expr *Arg = Args[ArgIdx++];
3360 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003361
Douglas Gregor7825bf32011-01-06 22:09:01 +00003362 unsigned TDF = 0;
3363 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3364 ParamType, ArgType, Arg,
3365 TDF))
3366 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Douglas Gregor0c83c812011-10-09 22:06:46 +00003368 // If we have nothing to deduce, we're done.
3369 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3370 continue;
3371
Sebastian Redl43144e72012-01-17 22:49:58 +00003372 // If the argument is an initializer list ...
3373 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3374 // ... then the parameter is an undeduced context, unless the parameter
3375 // type is (reference to cv) std::initializer_list<P'>, in which case
3376 // deduction is done for each element of the initializer list, and the
3377 // result is the deduced type if it's the same for all elements.
3378 QualType X;
3379 // Removing references was already done.
3380 if (!isStdInitializerList(ParamType, &X))
3381 continue;
3382
3383 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3384 if (TemplateDeductionResult Result =
Sebastian Redl19181662012-03-15 21:40:51 +00003385 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3386 ILE->getInit(i),
3387 Info, Deduced, TDF))
Sebastian Redl43144e72012-01-17 22:49:58 +00003388 return Result;
3389 }
3390 // Don't track the argument type, since an initializer list has none.
3391 continue;
3392 }
3393
Douglas Gregore65aacb2011-06-16 16:50:48 +00003394 // Keep track of the argument type and corresponding parameter index,
3395 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003396 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3397 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003398
Douglas Gregor7825bf32011-01-06 22:09:01 +00003399 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003400 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3401 ParamType, ArgType,
3402 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003403 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Douglas Gregor7825bf32011-01-06 22:09:01 +00003405 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409 // For a function parameter pack that occurs at the end of the
3410 // parameter-declaration-list, the type A of each remaining argument of
3411 // the call is compared with the type P of the declarator-id of the
3412 // function parameter pack. Each comparison deduces template arguments
3413 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003414 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003416 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003417 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003418 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor7825bf32011-01-06 22:09:01 +00003420 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003421 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3422 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregor7825bf32011-01-06 22:09:01 +00003424 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003425 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003426 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregore65aacb2011-06-16 16:50:48 +00003428 QualType OrigParamType = ParamPattern;
3429 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003430 Expr *Arg = Args[ArgIdx];
3431 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003432
Douglas Gregor7825bf32011-01-06 22:09:01 +00003433 unsigned TDF = 0;
3434 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3435 ParamType, ArgType, Arg,
3436 TDF)) {
3437 // We can't actually perform any deduction for this argument, so stop
3438 // deduction at this point.
3439 ++ArgIdx;
3440 break;
3441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Sebastian Redl43144e72012-01-17 22:49:58 +00003443 // As above, initializer lists need special handling.
3444 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3445 QualType X;
3446 if (!isStdInitializerList(ParamType, &X)) {
3447 ++ArgIdx;
3448 break;
3449 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003450
Sebastian Redl43144e72012-01-17 22:49:58 +00003451 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3452 if (TemplateDeductionResult Result =
3453 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3454 ILE->getInit(i)->getType(),
3455 Info, Deduced, TDF))
3456 return Result;
3457 }
3458 } else {
3459
3460 // Keep track of the argument type and corresponding argument index,
3461 // so we can check for compatibility between the deduced A and A.
3462 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3463 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3464 ArgType));
3465
3466 if (TemplateDeductionResult Result
3467 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3468 ParamType, ArgType, Info,
3469 Deduced, TDF))
3470 return Result;
3471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Richard Smith0a80d572014-05-29 01:12:14 +00003473 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregor7825bf32011-01-06 22:09:01 +00003476 // Build argument packs for each of the parameter packs expanded by this
3477 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003478 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregor7825bf32011-01-06 22:09:01 +00003481 // After we've matching against a parameter pack, we're done.
3482 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003483 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003484
Mike Stump11289f42009-09-09 15:08:12 +00003485 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003486 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003487 Info, &OriginalCallArgs,
3488 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003489}
3490
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003491QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3492 QualType FunctionType) {
3493 if (ArgFunctionType.isNull())
3494 return ArgFunctionType;
3495
3496 const FunctionProtoType *FunctionTypeP =
3497 FunctionType->castAs<FunctionProtoType>();
3498 CallingConv CC = FunctionTypeP->getCallConv();
3499 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3500 const FunctionProtoType *ArgFunctionTypeP =
3501 ArgFunctionType->getAs<FunctionProtoType>();
3502 if (ArgFunctionTypeP->getCallConv() == CC &&
3503 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3504 return ArgFunctionType;
3505
3506 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3507 EI = EI.withNoReturn(NoReturn);
3508 ArgFunctionTypeP =
3509 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3510 return QualType(ArgFunctionTypeP, 0);
3511}
3512
Douglas Gregor9b146582009-07-08 20:55:45 +00003513/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003514/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3515/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003516///
3517/// \param FunctionTemplate the function template for which we are performing
3518/// template argument deduction.
3519///
James Dennett18348b62012-06-22 08:52:37 +00003520/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003521/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003522///
3523/// \param ArgFunctionType the function type that will be used as the
3524/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003525/// function template's function type. This type may be NULL, if there is no
3526/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003527///
3528/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003529/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003530/// template argument deduction.
3531///
3532/// \param Info the argument will be updated to provide additional information
3533/// about template argument deduction.
3534///
3535/// \returns the result of template argument deduction.
3536Sema::TemplateDeductionResult
3537Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003538 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003539 QualType ArgFunctionType,
3540 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003541 TemplateDeductionInfo &Info,
3542 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003543 if (FunctionTemplate->isInvalidDecl())
3544 return TDK_Invalid;
3545
Douglas Gregor9b146582009-07-08 20:55:45 +00003546 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3547 TemplateParameterList *TemplateParams
3548 = FunctionTemplate->getTemplateParameters();
3549 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003550 if (!InOverloadResolution)
3551 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003552
Douglas Gregor9b146582009-07-08 20:55:45 +00003553 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003554 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003555 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003556 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003557 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003558 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003559 if (TemplateDeductionResult Result
3560 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003561 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003562 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003563 &FunctionType, Info))
3564 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003565
3566 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003567 }
3568
Eli Friedman77dcc722012-02-08 03:07:05 +00003569 // Unevaluated SFINAE context.
3570 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003571 SFINAETrap Trap(*this);
3572
John McCallc1f69982010-02-02 02:21:27 +00003573 Deduced.resize(TemplateParams->size());
3574
Richard Smith2a7d4812013-05-04 07:00:32 +00003575 // If the function has a deduced return type, substitute it for a dependent
3576 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003577 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003578 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003579 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003580 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003581 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003582 }
3583
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003584 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003585 unsigned TDF = TDF_TopLevelParameterTypeList;
3586 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003587 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003588 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003589 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003590 FunctionType, ArgFunctionType,
3591 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003592 return Result;
3593 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003594
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003596 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3597 NumExplicitlySpecified,
3598 Specialization, Info))
3599 return Result;
3600
Richard Smith2a7d4812013-05-04 07:00:32 +00003601 // If the function has a deduced return type, deduce it now, so we can check
3602 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003603 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003604 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003605 DeduceReturnType(Specialization, Info.getLocation(), false))
3606 return TDK_MiscellaneousDeductionFailure;
3607
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003608 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003609 // specialization with respect to arguments of compatible pointer to function
3610 // types, template argument deduction fails.
3611 if (!ArgFunctionType.isNull()) {
3612 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3613 Context.getCanonicalType(Specialization->getType()),
3614 Context.getCanonicalType(ArgFunctionType)))
3615 return TDK_MiscellaneousDeductionFailure;
3616 else if(!InOverloadResolution &&
3617 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3618 return TDK_MiscellaneousDeductionFailure;
3619 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003620
3621 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003622}
3623
Faisal Vali850da1a2013-09-29 17:08:32 +00003624/// \brief Given a function declaration (e.g. a generic lambda conversion
3625/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003626/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3627/// to replace 'auto' with and not the actual result type you want
3628/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003629static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003630SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003631 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003632 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003633 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003634 assert(AutoResultType->getContainedAutoType());
3635 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003636 TypeToReplaceAutoWith);
3637 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3638}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639
3640/// \brief Given a specialized conversion operator of a generic lambda
3641/// create the corresponding specializations of the call operator and
3642/// the static-invoker. If the return type of the call operator is auto,
3643/// deduce its return type and check if that matches the
3644/// return type of the destination function ptr.
3645
3646static inline Sema::TemplateDeductionResult
3647SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3648 CXXConversionDecl *ConversionSpecialized,
3649 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3650 QualType ReturnTypeOfDestFunctionPtr,
3651 TemplateDeductionInfo &TDInfo,
3652 Sema &S) {
3653
3654 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3655 assert(LambdaClass && LambdaClass->isGenericLambda());
3656
3657 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003658 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003659 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3660 CallOpResultType->getContainedAutoType();
3661
3662 FunctionTemplateDecl *CallOpTemplate =
3663 CallOpGeneric->getDescribedFunctionTemplate();
3664
Craig Topperc3ec1492014-05-26 06:22:03 +00003665 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003666 // Use the deduced arguments of the conversion function, to specialize our
3667 // generic lambda's call operator.
3668 if (Sema::TemplateDeductionResult Result
3669 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3670 DeducedArguments,
3671 0, CallOpSpecialized, TDInfo))
3672 return Result;
3673
3674 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003675 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3676 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003677 S.DeduceReturnType(CallOpSpecialized,
3678 CallOpSpecialized->getPointOfInstantiation(),
3679 /*Diagnose*/ true);
3680
3681 // Check to see if the return type of the destination ptr-to-function
3682 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003683 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003684 ReturnTypeOfDestFunctionPtr))
3685 return Sema::TDK_NonDeducedMismatch;
3686 // Since we have succeeded in matching the source and destination
3687 // ptr-to-functions (now including return type), and have successfully
3688 // specialized our corresponding call operator, we are ready to
3689 // specialize the static invoker with the deduced arguments of our
3690 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003691 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003692 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3693 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3694
3695 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result
3696 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3697 InvokerSpecialized, TDInfo);
3698 assert(Result == Sema::TDK_Success &&
3699 "If the call operator succeeded so should the invoker!");
3700 // Set the result type to match the corresponding call operator
3701 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003702 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3703 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003704 // Be sure to get the type to replace 'auto' with and not
3705 // the full result type of the call op specialization
3706 // to substitute into the 'auto' of the invoker and conversion
3707 // function.
3708 // For e.g.
3709 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3710 // We don't want to subst 'int*' into 'auto' to get int**.
3711
Alp Toker314cc812014-01-25 16:55:45 +00003712 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3713 ->getContainedAutoType()
3714 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003715 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3716 TypeToReplaceAutoWith, S);
3717 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3718 TypeToReplaceAutoWith, S);
3719 }
3720
3721 // Ensure that static invoker doesn't have a const qualifier.
3722 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3723 // do not use the CallOperator's TypeSourceInfo which allows
3724 // the const qualifier to leak through.
3725 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3726 getType().getTypePtr()->castAs<FunctionProtoType>();
3727 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3728 EPI.TypeQuals = 0;
3729 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003730 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003731 return Sema::TDK_Success;
3732}
Douglas Gregor05155d82009-08-21 23:19:43 +00003733/// \brief Deduce template arguments for a templated conversion
3734/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3735/// conversion function template specialization.
3736Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003737Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003738 QualType ToType,
3739 CXXConversionDecl *&Specialization,
3740 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003741 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003742 return TDK_Invalid;
3743
Faisal Vali2b3a3012013-10-24 23:40:02 +00003744 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003745 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3746
Faisal Vali2b3a3012013-10-24 23:40:02 +00003747 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003748
3749 // Canonicalize the types for deduction.
3750 QualType P = Context.getCanonicalType(FromType);
3751 QualType A = Context.getCanonicalType(ToType);
3752
Douglas Gregord99609a2011-03-06 09:03:20 +00003753 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003754 // If P is a reference type, the type referred to by P is used for
3755 // type deduction.
3756 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3757 P = PRef->getPointeeType();
3758
Douglas Gregord99609a2011-03-06 09:03:20 +00003759 // C++0x [temp.deduct.conv]p4:
3760 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003761 // for type deduction.
3762 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003763 A = ARef->getPointeeType().getUnqualifiedType();
3764 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003765 //
Mike Stump11289f42009-09-09 15:08:12 +00003766 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003767 else {
3768 assert(!A->isReferenceType() && "Reference types were handled above");
3769
3770 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003771 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003772 // of P for type deduction; otherwise,
3773 if (P->isArrayType())
3774 P = Context.getArrayDecayedType(P);
3775 // - If P is a function type, the pointer type produced by the
3776 // function-to-pointer standard conversion (4.3) is used in
3777 // place of P for type deduction; otherwise,
3778 else if (P->isFunctionType())
3779 P = Context.getPointerType(P);
3780 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003781 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003782 else
3783 P = P.getUnqualifiedType();
3784
Douglas Gregord99609a2011-03-06 09:03:20 +00003785 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003786 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003787 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003788 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003789 A = A.getUnqualifiedType();
3790 }
3791
Eli Friedman77dcc722012-02-08 03:07:05 +00003792 // Unevaluated SFINAE context.
3793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003794 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003795
3796 // C++ [temp.deduct.conv]p1:
3797 // Template argument deduction is done by comparing the return
3798 // type of the template conversion function (call it P) with the
3799 // type that is required as the result of the conversion (call it
3800 // A) as described in 14.8.2.4.
3801 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003802 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003803 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003804 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003805
3806 // C++0x [temp.deduct.conv]p4:
3807 // In general, the deduction process attempts to find template
3808 // argument values that will make the deduced A identical to
3809 // A. However, there are two cases that allow a difference:
3810 unsigned TDF = 0;
3811 // - If the original A is a reference type, A can be more
3812 // cv-qualified than the deduced A (i.e., the type referred to
3813 // by the reference)
3814 if (ToType->isReferenceType())
3815 TDF |= TDF_ParamWithReferenceType;
3816 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003817 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003818 // conversion.
3819 //
3820 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3821 // both P and A are pointers or member pointers. In this case, we
3822 // just ignore cv-qualifiers completely).
3823 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003824 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003825 TDF |= TDF_IgnoreQualifiers;
3826 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003827 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3828 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003829 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003830
3831 // Create an Instantiation Scope for finalizing the operator.
3832 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003833 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003834 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003835 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003836 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3837 ConversionSpecialized, Info);
3838 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3839
3840 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003841 // to a ptr-to-function, use the deduced arguments from the conversion
3842 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003843 // e.g., int (*fp)(int) = [](auto a) { return a; };
3844 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3845
3846 // Get the return type of the destination ptr-to-function we are converting
3847 // to. This is necessary for matching the lambda call operator's return
3848 // type to that of the destination ptr-to-function's return type.
3849 assert(A->isPointerType() &&
3850 "Can only convert from lambda to ptr-to-function");
3851 const FunctionType *ToFunType =
3852 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003853 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3854
Faisal Vali2b3a3012013-10-24 23:40:02 +00003855 // Create the corresponding specializations of the call operator and
3856 // the static-invoker; and if the return type is auto,
3857 // deduce the return type and check if it matches the
3858 // DestFunctionPtrReturnType.
3859 // For instance:
3860 // auto L = [](auto a) { return f(a); };
3861 // int (*fp)(int) = L;
3862 // char (*fp2)(int) = L; <-- Not OK.
3863
3864 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3865 Specialization, Deduced, DestFunctionPtrReturnType,
3866 Info, *this);
3867 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003868 return Result;
3869}
3870
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003871/// \brief Deduce template arguments for a function template when there is
3872/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3873///
3874/// \param FunctionTemplate the function template for which we are performing
3875/// template argument deduction.
3876///
James Dennett18348b62012-06-22 08:52:37 +00003877/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003878/// arguments.
3879///
3880/// \param Specialization if template argument deduction was successful,
3881/// this will be set to the function template specialization produced by
3882/// template argument deduction.
3883///
3884/// \param Info the argument will be updated to provide additional information
3885/// about template argument deduction.
3886///
3887/// \returns the result of template argument deduction.
3888Sema::TemplateDeductionResult
3889Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003890 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003891 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003892 TemplateDeductionInfo &Info,
3893 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003894 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003895 QualType(), Specialization, Info,
3896 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003897}
3898
Richard Smith30482bc2011-02-20 03:19:35 +00003899namespace {
3900 /// Substitute the 'auto' type specifier within a type for a given replacement
3901 /// type.
3902 class SubstituteAutoTransform :
3903 public TreeTransform<SubstituteAutoTransform> {
3904 QualType Replacement;
3905 public:
Nico Weberc153d242014-07-28 00:02:09 +00003906 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3907 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3908 Replacement(Replacement) {}
3909
Richard Smith30482bc2011-02-20 03:19:35 +00003910 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3911 // If we're building the type pattern to deduce against, don't wrap the
3912 // substituted type in an AutoType. Certain template deduction rules
3913 // apply only when a template type parameter appears directly (and not if
3914 // the parameter is found through desugaring). For instance:
3915 // auto &&lref = lvalue;
3916 // must transform into "rvalue reference to T" not "rvalue reference to
3917 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003918 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003919 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003920 TemplateTypeParmTypeLoc NewTL =
3921 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003922 NewTL.setNameLoc(TL.getNameLoc());
3923 return Result;
3924 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003925 bool Dependent =
3926 !Replacement.isNull() && Replacement->isDependentType();
3927 QualType Result =
3928 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3929 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003930 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003931 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3932 NewTL.setNameLoc(TL.getNameLoc());
3933 return Result;
3934 }
3935 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003936
3937 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3938 // Lambdas never need to be transformed.
3939 return E;
3940 }
Richard Smith061f1e22013-04-30 21:23:01 +00003941
Richard Smith2a7d4812013-05-04 07:00:32 +00003942 QualType Apply(TypeLoc TL) {
3943 // Create some scratch storage for the transformed type locations.
3944 // FIXME: We're just going to throw this information away. Don't build it.
3945 TypeLocBuilder TLB;
3946 TLB.reserve(TL.getFullDataSize());
3947 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003948 }
Richard Smith30482bc2011-02-20 03:19:35 +00003949 };
3950}
3951
Richard Smith2a7d4812013-05-04 07:00:32 +00003952Sema::DeduceAutoResult
3953Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3954 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3955}
3956
Richard Smith061f1e22013-04-30 21:23:01 +00003957/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003958///
3959/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003960/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003961/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003962/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003963Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003964Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003965 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003966 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3967 if (NonPlaceholder.isInvalid())
3968 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003969 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003970 }
3971
Richard Smith2a7d4812013-05-04 07:00:32 +00003972 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003973 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003974 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003975 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003976 }
3977
Richard Smith74aeef52013-04-26 16:15:35 +00003978 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3979 // Since 'decltype(auto)' can only occur at the top of the type, we
3980 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003981 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003982 if (AT->isDecltypeAuto()) {
3983 if (isa<InitListExpr>(Init)) {
3984 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3985 return DAR_FailedAlreadyDiagnosed;
3986 }
3987
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003988 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
Richard Smith74aeef52013-04-26 16:15:35 +00003989 // FIXME: Support a non-canonical deduced type for 'auto'.
3990 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003991 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003992 if (Result.isNull())
3993 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003994 return DAR_Succeeded;
3995 }
3996 }
3997
Richard Smith30482bc2011-02-20 03:19:35 +00003998 SourceLocation Loc = Init->getExprLoc();
3999
4000 LocalInstantiationScope InstScope(*this);
4001
4002 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004003 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004004 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4005 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004006 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4007 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00004008 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
4009 Loc);
4010
Richard Smith061f1e22013-04-30 21:23:01 +00004011 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4012 assert(!FuncParam.isNull() &&
4013 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004014
4015 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004016 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004017 Deduced.resize(1);
4018 QualType InitType = Init->getType();
4019 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004020
Craig Toppere6706e42012-09-19 02:26:47 +00004021 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004022
Richard Smith74801c82012-07-08 04:13:07 +00004023 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004024 if (InitList) {
4025 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004026 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004027 TemplArg,
4028 InitList->getInit(i),
4029 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004030 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004031 }
4032 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004033 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4034 FuncParam, InitType, Init,
4035 TDF))
4036 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004037
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004038 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4039 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004040 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004041 }
Richard Smith30482bc2011-02-20 03:19:35 +00004042
Eli Friedmane4310952012-11-06 23:56:42 +00004043 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004044 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004045
Eli Friedmane4310952012-11-06 23:56:42 +00004046 QualType DeducedType = Deduced[0].getAsType();
4047
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004048 if (InitList) {
4049 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4050 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004051 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004052 }
4053
Richard Smith061f1e22013-04-30 21:23:01 +00004054 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004055 if (Result.isNull())
4056 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004057
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004058 // Check that the deduced argument type is compatible with the original
4059 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004060 if (!InitList && !Result.isNull() &&
4061 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004062 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004063 Result)) {
4064 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004065 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004066 }
4067
Sebastian Redl09edce02012-01-23 22:09:39 +00004068 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004069}
4070
Faisal Vali2b391ab2013-09-26 19:54:12 +00004071QualType Sema::SubstAutoType(QualType TypeWithAuto,
4072 QualType TypeToReplaceAuto) {
4073 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4074 TransformType(TypeWithAuto);
4075}
4076
4077TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4078 QualType TypeToReplaceAuto) {
4079 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4080 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004081}
4082
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004083void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4084 if (isa<InitListExpr>(Init))
4085 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004086 VDecl->isInitCapture()
4087 ? diag::err_init_capture_deduction_failure_from_init_list
4088 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004089 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4090 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004091 Diag(VDecl->getLocation(),
4092 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4093 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004094 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4095 << Init->getSourceRange();
4096}
4097
Richard Smith2a7d4812013-05-04 07:00:32 +00004098bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4099 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004100 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004101
4102 if (FD->getTemplateInstantiationPattern())
4103 InstantiateFunctionDefinition(Loc, FD);
4104
Alp Toker314cc812014-01-25 16:55:45 +00004105 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004106 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4107 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4108 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4109 }
4110
4111 return StillUndeduced;
4112}
4113
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004114static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004115MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004116 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004117 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004118 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
4120/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004121static void
4122AddImplicitObjectParameterType(ASTContext &Context,
4123 CXXMethodDecl *Method,
4124 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004125 // C++11 [temp.func.order]p3:
4126 // [...] The new parameter is of type "reference to cv A," where cv are
4127 // the cv-qualifiers of the function template (if any) and A is
4128 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004129 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004130 // The standard doesn't say explicitly, but we pick the appropriate kind of
4131 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004132 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4133 ArgTy = Context.getQualifiedType(ArgTy,
4134 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004135 if (Method->getRefQualifier() == RQ_RValue)
4136 ArgTy = Context.getRValueReferenceType(ArgTy);
4137 else
4138 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004139 ArgTypes.push_back(ArgTy);
4140}
4141
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004142/// \brief Determine whether the function template \p FT1 is at least as
4143/// specialized as \p FT2.
4144static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004145 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004146 FunctionTemplateDecl *FT1,
4147 FunctionTemplateDecl *FT2,
4148 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004149 unsigned NumCallArguments1,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004150 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004151 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004153 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4154 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004156 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4157 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004158 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004159 Deduced.resize(TemplateParams->size());
4160
4161 // C++0x [temp.deduct.partial]p3:
4162 // The types used to determine the ordering depend on the context in which
4163 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004164 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004165 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004166 switch (TPOC) {
4167 case TPOC_Call: {
4168 // - In the context of a function call, the function parameter types are
4169 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004170 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4171 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004172
Eli Friedman3b5774a2012-09-19 23:27:04 +00004173 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004174 // [...] If only one of the function templates is a non-static
4175 // member, that function template is considered to have a new
4176 // first parameter inserted in its function parameter list. The
4177 // new parameter is of type "reference to cv A," where cv are
4178 // the cv-qualifiers of the function template (if any) and A is
4179 // the class of which the function template is a member.
4180 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004181 // Note that we interpret this to mean "if one of the function
4182 // templates is a non-static member and the other is a non-member";
4183 // otherwise, the ordering rules for static functions against non-static
4184 // functions don't make any sense.
4185 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004186 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4187 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004188 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004189
Richard Smithe5b52202013-09-11 00:52:39 +00004190 unsigned NumComparedArguments = NumCallArguments1;
4191
4192 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004193 // Compare 'this' from Method1 against first parameter from Method2.
4194 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4195 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004196 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004197 // Compare 'this' from Method2 against first parameter from Method1.
4198 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004199 }
4200
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004201 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004202 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004203 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004204 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregorb837ea42011-01-11 17:34:58 +00004206 // C++ [temp.func.order]p5:
4207 // The presence of unused ellipsis and default arguments has no effect on
4208 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004209 if (Args1.size() > NumComparedArguments)
4210 Args1.resize(NumComparedArguments);
4211 if (Args2.size() > NumComparedArguments)
4212 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004213 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4214 Args1.data(), Args1.size(), Info, Deduced,
4215 TDF_None, /*PartialOrdering=*/true,
Douglas Gregor63814022011-01-21 17:29:42 +00004216 RefParamComparisons))
Richard Smith0a80d572014-05-29 01:12:14 +00004217 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004219 break;
4220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004222 case TPOC_Conversion:
4223 // - In the context of a call to a conversion operator, the return types
4224 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004225 if (DeduceTemplateArgumentsByTypeMatch(
4226 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4227 Info, Deduced, TDF_None,
4228 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004229 return false;
4230 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004232 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004233 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004234 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004235 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4236 FD2->getType(), FD1->getType(),
4237 Info, Deduced, TDF_None,
4238 /*PartialOrdering=*/true,
4239 RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004240 return false;
4241 break;
4242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004244 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 // In most cases, all template parameters must have values in order for
4246 // deduction to succeed, but for partial ordering purposes a template
4247 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004248 // types being used for partial ordering. [ Note: a template parameter used
4249 // in a non-deduced context is considered used. -end note]
4250 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4251 for (; ArgIdx != NumArgs; ++ArgIdx)
4252 if (Deduced[ArgIdx].isNull())
4253 break;
4254
4255 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004257 // as FT2.
4258 return true;
4259 }
4260
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004261 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004262 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004263 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004264 case TPOC_Call:
4265 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4266 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004267 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004268 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004269 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004271 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004272 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4273 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004277 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004278 TemplateParams->getDepth(),
4279 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004280 break;
4281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 for (; ArgIdx != NumArgs; ++ArgIdx)
4284 // If this argument had no value deduced but was used in one of the types
4285 // used for partial ordering, then deduction fails.
4286 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4287 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004289 return true;
4290}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregorcef1a032011-01-16 16:03:23 +00004292/// \brief Determine whether this a function template whose parameter-type-list
4293/// ends with a function parameter pack.
4294static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4295 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4296 unsigned NumParams = Function->getNumParams();
4297 if (NumParams == 0)
4298 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregorcef1a032011-01-16 16:03:23 +00004300 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4301 if (!Last->isParameterPack())
4302 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303
Douglas Gregorcef1a032011-01-16 16:03:23 +00004304 // Make sure that no previous parameter is a parameter pack.
4305 while (--NumParams > 0) {
4306 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4307 return false;
4308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregorcef1a032011-01-16 16:03:23 +00004310 return true;
4311}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
Douglas Gregorbe999392009-09-15 16:23:51 +00004313/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004314/// to the rules of function template partial ordering (C++ [temp.func.order]).
4315///
4316/// \param FT1 the first function template
4317///
4318/// \param FT2 the second function template
4319///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004320/// \param TPOC the context in which we are performing partial ordering of
4321/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004322///
Richard Smithe5b52202013-09-11 00:52:39 +00004323/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4324/// only when \c TPOC is \c TPOC_Call.
4325///
4326/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4327/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004328///
Douglas Gregorbe999392009-09-15 16:23:51 +00004329/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004330/// template is more specialized, returns NULL.
4331FunctionTemplateDecl *
4332Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4333 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004334 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004335 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004336 unsigned NumCallArguments1,
4337 unsigned NumCallArguments2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004338 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Craig Topperc3ec1492014-05-26 06:22:03 +00004340 NumCallArguments1, nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004342 NumCallArguments2,
Douglas Gregor63814022011-01-21 17:29:42 +00004343 &RefParamComparisons);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004345 if (Better1 != Better2) // We have a clear winner
4346 return Better1? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004348 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004349 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004350
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004351 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352 // If for each type being considered a given template is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354 // the other template is not more specialized for any types or is not at
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004355 // least as specialized for any types, then the given template is more
4356 // specialized than the other template. Otherwise, neither template is more
4357 // specialized than the other.
4358 Better1 = false;
4359 Better2 = false;
Douglas Gregor63814022011-01-21 17:29:42 +00004360 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004361 // C++0x [temp.deduct.partial]p9:
4362 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregor63814022011-01-21 17:29:42 +00004363 // types are identical after the transformations above) and both P and A
4364 // were reference types (before being replaced with the type referred to
4365 // above):
4366
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367 // -- if the type from the argument template was an lvalue reference
Douglas Gregor63814022011-01-21 17:29:42 +00004368 // and the type from the parameter template was not, the argument
4369 // type is considered to be more specialized than the other;
4370 // otherwise,
4371 if (!RefParamComparisons[I].ArgIsRvalueRef &&
4372 RefParamComparisons[I].ParamIsRvalueRef) {
4373 Better2 = true;
4374 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004375 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004376 continue;
4377 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
4378 RefParamComparisons[I].ArgIsRvalueRef) {
4379 Better1 = true;
4380 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004381 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004382 continue;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregor63814022011-01-21 17:29:42 +00004385 // -- if the type from the argument template is more cv-qualified than
4386 // the type from the parameter template (as described above), the
4387 // argument type is considered to be more specialized than the
4388 // other; otherwise,
4389 switch (RefParamComparisons[I].Qualifiers) {
4390 case NeitherMoreQualified:
4391 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregor63814022011-01-21 17:29:42 +00004393 case ParamMoreQualified:
4394 Better1 = true;
4395 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004396 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004397 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor63814022011-01-21 17:29:42 +00004399 case ArgMoreQualified:
4400 Better2 = true;
4401 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004402 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004403 continue;
4404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregor63814022011-01-21 17:29:42 +00004406 // -- neither type is more specialized than the other.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004409 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00004410 if (Better1)
4411 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004412 else if (Better2)
4413 return FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Douglas Gregorcef1a032011-01-16 16:03:23 +00004415 // FIXME: This mimics what GCC implements, but doesn't match up with the
4416 // proposed resolution for core issue 692. This area needs to be sorted out,
4417 // but for now we attempt to maintain compatibility.
4418 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4419 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4420 if (Variadic1 != Variadic2)
4421 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Craig Topperc3ec1492014-05-26 06:22:03 +00004423 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004424}
Douglas Gregor9b146582009-07-08 20:55:45 +00004425
Douglas Gregor450f00842009-09-25 18:43:00 +00004426/// \brief Determine if the two templates are equivalent.
4427static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4428 if (T1 == T2)
4429 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregor450f00842009-09-25 18:43:00 +00004431 if (!T1 || !T2)
4432 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregor450f00842009-09-25 18:43:00 +00004434 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4435}
4436
4437/// \brief Retrieve the most specialized of the given function template
4438/// specializations.
4439///
John McCall58cc69d2010-01-27 01:50:18 +00004440/// \param SpecBegin the start iterator of the function template
4441/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004442///
John McCall58cc69d2010-01-27 01:50:18 +00004443/// \param SpecEnd the end iterator of the function template
4444/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004445///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004447/// diagnostic should occur.
4448///
4449/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4450/// no matching candidates.
4451///
4452/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4453/// occurs.
4454///
4455/// \param CandidateDiag partial diagnostic used for each function template
4456/// specialization that is a candidate in the ambiguous ordering. One parameter
4457/// in this diagnostic should be unbound, which will correspond to the string
4458/// describing the template arguments for the function template specialization.
4459///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004461/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004462UnresolvedSetIterator Sema::getMostSpecialized(
4463 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4464 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004465 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4466 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4467 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004468 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004469 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004470 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004471 FailedCandidates.NoteCandidates(*this, Loc);
4472 }
John McCall58cc69d2010-01-27 01:50:18 +00004473 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
4476 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004477 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 // Find the function template that is better than all of the templates it
4480 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004481 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004483 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004484 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004485 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4486 FunctionTemplateDecl *Challenger
4487 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004488 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004489 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004490 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004491 Challenger)) {
4492 Best = I;
4493 BestTemplate = Challenger;
4494 }
4495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Douglas Gregor450f00842009-09-25 18:43:00 +00004497 // Make sure that the "best" function template is more specialized than all
4498 // of the others.
4499 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004500 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4501 FunctionTemplateDecl *Challenger
4502 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004503 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004505 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004506 BestTemplate)) {
4507 Ambiguous = true;
4508 break;
4509 }
4510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregor450f00842009-09-25 18:43:00 +00004512 if (!Ambiguous) {
4513 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004514 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Douglas Gregor450f00842009-09-25 18:43:00 +00004517 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004518 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004519 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Richard Smithb875c432013-05-04 01:51:08 +00004521 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004522 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4523 PartialDiagnostic PD = CandidateDiag;
4524 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004525 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004526 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004527 if (!TargetType.isNull())
4528 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4529 TargetType);
4530 Diag((*I)->getLocation(), PD);
4531 }
Richard Smithb875c432013-05-04 01:51:08 +00004532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
John McCall58cc69d2010-01-27 01:50:18 +00004534 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004535}
4536
Douglas Gregorbe999392009-09-15 16:23:51 +00004537/// \brief Returns the more specialized class template partial specialization
4538/// according to the rules of partial ordering of class template partial
4539/// specializations (C++ [temp.class.order]).
4540///
4541/// \param PS1 the first class template partial specialization
4542///
4543/// \param PS2 the second class template partial specialization
4544///
4545/// \returns the more specialized class template partial specialization. If
4546/// neither partial specialization is more specialized, returns NULL.
4547ClassTemplatePartialSpecializationDecl *
4548Sema::getMoreSpecializedPartialSpecialization(
4549 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004550 ClassTemplatePartialSpecializationDecl *PS2,
4551 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004552 // C++ [temp.class.order]p1:
4553 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 // specialized as the second if, given the following rewrite to two
4555 // function templates, the first function template is at least as
4556 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004557 // templates (14.6.6.2):
4558 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559 // first partial specialization and has a single function parameter
4560 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004561 // arguments of the first partial specialization, and
4562 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563 // second partial specialization and has a single function parameter
4564 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004565 // arguments of the second partial specialization.
4566 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004567 // Rather than synthesize function templates, we merely perform the
4568 // equivalent partial ordering by performing deduction directly on
4569 // the template arguments of the class template partial
4570 // specializations. This computation is slightly simpler than the
4571 // general problem of function template partial ordering, because
4572 // class template partial specializations are more constrained. We
4573 // know that every template parameter is deducible from the class
4574 // template partial specialization's template arguments, for
4575 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004576 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004577 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004578
4579 QualType PT1 = PS1->getInjectedSpecializationType();
4580 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
Douglas Gregorbe999392009-09-15 16:23:51 +00004582 // Determine whether PS1 is at least as specialized as PS2
4583 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004584 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4585 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004586 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004588 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004589 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004590 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004591 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004592 Better1 = !::FinishTemplateArgumentDeduction(
4593 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4594 }
4595
4596 // Determine whether PS2 is at least as specialized as PS1
4597 Deduced.clear();
4598 Deduced.resize(PS1->getTemplateParameters()->size());
4599 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4600 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4601 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004602 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004603 if (Better2) {
4604 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4605 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004606 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004607 Better2 = !::FinishTemplateArgumentDeduction(
4608 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4609 }
4610
4611 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004612 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004613
4614 return Better1 ? PS1 : PS2;
4615}
4616
Larisse Voufo30616382013-08-23 22:21:36 +00004617/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4618/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4619/// VarTemplate(Partial)SpecializationDecl with a new data
4620/// structure Template(Partial)SpecializationDecl, and
4621/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004622VarTemplatePartialSpecializationDecl *
4623Sema::getMoreSpecializedPartialSpecialization(
4624 VarTemplatePartialSpecializationDecl *PS1,
4625 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4626 SmallVector<DeducedTemplateArgument, 4> Deduced;
4627 TemplateDeductionInfo Info(Loc);
4628
Richard Smithf04fd0b2013-12-12 23:14:16 +00004629 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004630 "the partial specializations being compared should specialize"
4631 " the same template.");
4632 TemplateName Name(PS1->getSpecializedTemplate());
4633 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4634 QualType PT1 = Context.getTemplateSpecializationType(
4635 CanonTemplate, PS1->getTemplateArgs().data(),
4636 PS1->getTemplateArgs().size());
4637 QualType PT2 = Context.getTemplateSpecializationType(
4638 CanonTemplate, PS2->getTemplateArgs().data(),
4639 PS2->getTemplateArgs().size());
4640
4641 // Determine whether PS1 is at least as specialized as PS2
4642 Deduced.resize(PS2->getTemplateParameters()->size());
4643 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4644 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4645 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004646 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004647 if (Better1) {
4648 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4649 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004650 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4652 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004653 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655
Douglas Gregorbe999392009-09-15 16:23:51 +00004656 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004657 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004658 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004659 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4660 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004661 PT1, PT2, Info, Deduced, TDF_None,
4662 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004663 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004664 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004665 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004666 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4668 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004669 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregorbe999392009-09-15 16:23:51 +00004672 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004673 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregorbe999392009-09-15 16:23:51 +00004675 return Better1? PS1 : PS2;
4676}
4677
Mike Stump11289f42009-09-09 15:08:12 +00004678static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004679MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004680 const TemplateArgument &TemplateArg,
4681 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004682 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004683 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004684
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004685/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004686/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004687static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004688MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004689 const Expr *E,
4690 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004691 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004692 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004693 // We can deduce from a pack expansion.
4694 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4695 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696
Richard Smith34349002012-07-09 03:07:20 +00004697 // Skip through any implicit casts we added while type-checking, and any
4698 // substitutions performed by template alias expansion.
4699 while (1) {
4700 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4701 E = ICE->getSubExpr();
4702 else if (const SubstNonTypeTemplateParmExpr *Subst =
4703 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4704 E = Subst->getReplacement();
4705 else
4706 break;
4707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
4709 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004710 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004711 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004712 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004713 return;
4714
Mike Stump11289f42009-09-09 15:08:12 +00004715 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004716 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4717 if (!NTTP)
4718 return;
4719
Douglas Gregor21610382009-10-29 00:04:11 +00004720 if (NTTP->getDepth() == Depth)
4721 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004722}
4723
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004724/// \brief Mark the template parameters that are used by the given
4725/// nested name specifier.
4726static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004727MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004728 NestedNameSpecifier *NNS,
4729 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004730 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004731 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732 if (!NNS)
4733 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004735 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004736 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004737 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004738 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004739}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741/// \brief Mark the template parameters that are used by the given
4742/// template name.
4743static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004744MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004745 TemplateName Name,
4746 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004747 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004748 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004749 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4750 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004751 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4752 if (TTP->getDepth() == Depth)
4753 Used[TTP->getIndex()] = true;
4754 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004755 return;
4756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004758 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004759 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004760 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004761 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004762 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004763 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004764}
4765
4766/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004767/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004768static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004769MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004770 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004771 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004772 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004773 if (T.isNull())
4774 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor91772d12009-06-13 00:26:55 +00004776 // Non-dependent types have nothing deducible
4777 if (!T->isDependentType())
4778 return;
4779
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004780 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004781 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004782 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004783 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004784 cast<PointerType>(T)->getPointeeType(),
4785 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004786 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004787 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004788 break;
4789
4790 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004791 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004792 cast<BlockPointerType>(T)->getPointeeType(),
4793 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004794 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004795 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004796 break;
4797
4798 case Type::LValueReference:
4799 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004800 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004801 cast<ReferenceType>(T)->getPointeeType(),
4802 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004803 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004804 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004805 break;
4806
4807 case Type::MemberPointer: {
4808 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004809 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004810 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004811 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004812 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004813 break;
4814 }
4815
4816 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004817 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004818 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004819 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004820 // Fall through to check the element type
4821
4822 case Type::ConstantArray:
4823 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004824 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004825 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004826 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004827 break;
4828
4829 case Type::Vector:
4830 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004832 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004833 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004834 break;
4835
Douglas Gregor758a8692009-06-17 21:51:59 +00004836 case Type::DependentSizedExtVector: {
4837 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004838 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004839 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004840 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004841 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004842 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004843 break;
4844 }
4845
Douglas Gregor91772d12009-06-13 00:26:55 +00004846 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004847 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004848 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4849 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004850 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4851 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004852 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004853 break;
4854 }
4855
Douglas Gregor21610382009-10-29 00:04:11 +00004856 case Type::TemplateTypeParm: {
4857 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4858 if (TTP->getDepth() == Depth)
4859 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004860 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004861 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004862
Douglas Gregorfb322d82011-01-14 05:11:40 +00004863 case Type::SubstTemplateTypeParmPack: {
4864 const SubstTemplateTypeParmPackType *Subst
4865 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004866 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004867 QualType(Subst->getReplacedParameter(), 0),
4868 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004869 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004870 OnlyDeduced, Depth, Used);
4871 break;
4872 }
4873
John McCall2408e322010-04-27 00:57:59 +00004874 case Type::InjectedClassName:
4875 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4876 // fall through
4877
Douglas Gregor91772d12009-06-13 00:26:55 +00004878 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004879 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004880 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004881 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004882 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Douglas Gregord0ad2942010-12-23 01:24:45 +00004884 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004885 // If the template argument list of P contains a pack expansion that is
4886 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004887 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004889 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4890 break;
4891
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004892 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004893 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004894 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004895 break;
4896 }
4897
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004898 case Type::Complex:
4899 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004900 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004901 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004902 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004903 break;
4904
Eli Friedman0dfb8892011-10-06 23:00:33 +00004905 case Type::Atomic:
4906 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004908 cast<AtomicType>(T)->getValueType(),
4909 OnlyDeduced, Depth, Used);
4910 break;
4911
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004912 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004913 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004914 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004915 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004916 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004917 break;
4918
John McCallc392f372010-06-11 00:33:02 +00004919 case Type::DependentTemplateSpecialization: {
4920 const DependentTemplateSpecializationType *Spec
4921 = cast<DependentTemplateSpecializationType>(T);
4922 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004923 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004924 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregord0ad2942010-12-23 01:24:45 +00004926 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927 // If the template argument list of P contains a pack expansion that is not
4928 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004929 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004931 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4932 break;
4933
John McCallc392f372010-06-11 00:33:02 +00004934 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004936 Used);
4937 break;
4938 }
4939
John McCallbd8d9bd2010-03-01 23:49:17 +00004940 case Type::TypeOf:
4941 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004942 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004943 cast<TypeOfType>(T)->getUnderlyingType(),
4944 OnlyDeduced, Depth, Used);
4945 break;
4946
4947 case Type::TypeOfExpr:
4948 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004949 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004950 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4951 OnlyDeduced, Depth, Used);
4952 break;
4953
4954 case Type::Decltype:
4955 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004956 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004957 cast<DecltypeType>(T)->getUnderlyingExpr(),
4958 OnlyDeduced, Depth, Used);
4959 break;
4960
Alexis Hunte852b102011-05-24 22:41:36 +00004961 case Type::UnaryTransform:
4962 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004963 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004964 cast<UnaryTransformType>(T)->getUnderlyingType(),
4965 OnlyDeduced, Depth, Used);
4966 break;
4967
Douglas Gregord2fa7662010-12-20 02:24:11 +00004968 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004969 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004970 cast<PackExpansionType>(T)->getPattern(),
4971 OnlyDeduced, Depth, Used);
4972 break;
4973
Richard Smith30482bc2011-02-20 03:19:35 +00004974 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004975 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004976 cast<AutoType>(T)->getDeducedType(),
4977 OnlyDeduced, Depth, Used);
4978
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004979 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004980 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004981 case Type::VariableArray:
4982 case Type::FunctionNoProto:
4983 case Type::Record:
4984 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004986 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004987 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004988 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004989#define TYPE(Class, Base)
4990#define ABSTRACT_TYPE(Class, Base)
4991#define DEPENDENT_TYPE(Class, Base)
4992#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4993#include "clang/AST/TypeNodes.def"
4994 break;
4995 }
4996}
4997
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004998/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004999/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005000static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005001MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005002 const TemplateArgument &TemplateArg,
5003 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005004 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005005 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005006 switch (TemplateArg.getKind()) {
5007 case TemplateArgument::Null:
5008 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005009 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005010 break;
Mike Stump11289f42009-09-09 15:08:12 +00005011
Eli Friedmanb826a002012-09-26 02:36:12 +00005012 case TemplateArgument::NullPtr:
5013 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5014 Depth, Used);
5015 break;
5016
Douglas Gregor91772d12009-06-13 00:26:55 +00005017 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005018 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005019 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005020 break;
5021
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005022 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005023 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005024 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005026 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005027 break;
5028
5029 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005030 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005031 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005032 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
Anders Carlssonbc343912009-06-15 17:04:53 +00005034 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005035 for (const auto &P : TemplateArg.pack_elements())
5036 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005037 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005038 }
5039}
5040
James Dennett41725122012-06-22 10:16:05 +00005041/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005042/// template argument list.
5043///
5044/// \param TemplateArgs the template argument list from which template
5045/// parameters will be deduced.
5046///
James Dennett41725122012-06-22 10:16:05 +00005047/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005048/// to indicate when the corresponding template parameter will be
5049/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005050void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005051Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005052 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005053 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005054 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055 // If the template argument list of P contains a pack expansion that is not
5056 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005057 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005059 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5060 return;
5061
Douglas Gregor91772d12009-06-13 00:26:55 +00005062 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005063 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005064 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005065}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005066
5067/// \brief Marks all of the template parameters that will be deduced by a
5068/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005069void Sema::MarkDeducedTemplateParameters(
5070 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5071 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005073 = FunctionTemplate->getTemplateParameters();
5074 Deduced.clear();
5075 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregorce23bae2009-09-18 23:21:38 +00005077 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5078 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005079 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005080 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005081}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005082
5083bool hasDeducibleTemplateParameters(Sema &S,
5084 FunctionTemplateDecl *FunctionTemplate,
5085 QualType T) {
5086 if (!T->isDependentType())
5087 return false;
5088
5089 TemplateParameterList *TemplateParams
5090 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005091 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005092 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005093 Deduced);
5094
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005095 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005096}