blob: 66b9abc3000c60ded957b34d86e7b622ec4e91c2 [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 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
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 Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000103 bool PartialOrdering = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000104
105static Sema::TemplateDeductionResult
106DeduceTemplateArguments(Sema &S,
107 TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000108 const TemplateArgument *Params, unsigned NumParams,
109 const TemplateArgument *Args, unsigned NumArgs,
110 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000112
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000113/// \brief If the given expression is of a form that permits the deduction
114/// of a non-type template parameter, return the declaration of that
115/// non-type template parameter.
116static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000117 // If we are within an alias template, the expression may have undergone
118 // any number of parameter substitutions already.
119 while (1) {
120 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
121 E = IC->getSubExpr();
122 else if (SubstNonTypeTemplateParmExpr *Subst =
123 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
124 E = Subst->getReplacement();
125 else
126 break;
127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000129 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
130 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000131
Craig Topperc3ec1492014-05-26 06:22:03 +0000132 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000133}
134
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000135/// \brief Determine whether two declaration pointers refer to the same
136/// declaration.
137static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000138 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
139 X = NX->getUnderlyingDecl();
140 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
141 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000142
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000143 return X->getCanonicalDecl() == Y->getCanonicalDecl();
144}
145
146/// \brief Verify that the given, deduced template arguments are compatible.
147///
148/// \returns The deduced template argument, or a NULL template argument if
149/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000151checkDeducedTemplateArguments(ASTContext &Context,
152 const DeducedTemplateArgument &X,
153 const DeducedTemplateArgument &Y) {
154 // We have no deduction for one or both of the arguments; they're compatible.
155 if (X.isNull())
156 return Y;
157 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000159
160 switch (X.getKind()) {
161 case TemplateArgument::Null:
162 llvm_unreachable("Non-deduced template arguments handled above");
163
164 case TemplateArgument::Type:
165 // If two template type arguments have the same type, they're compatible.
166 if (Y.getKind() == TemplateArgument::Type &&
167 Context.hasSameType(X.getAsType(), Y.getAsType()))
168 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000169
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000170 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000171
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000172 case TemplateArgument::Integral:
173 // If we deduced a constant in one case and either a dependent expression or
174 // declaration in another case, keep the integral constant.
175 // If both are integral constants with the same value, keep that value.
176 if (Y.getKind() == TemplateArgument::Expression ||
177 Y.getKind() == TemplateArgument::Declaration ||
178 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000179 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000181 X.wasDeducedFromArrayBound() &&
182 Y.wasDeducedFromArrayBound());
183
184 // All other combinations are incompatible.
185 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000187 case TemplateArgument::Template:
188 if (Y.getKind() == TemplateArgument::Template &&
189 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
190 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000192 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000194
195 case TemplateArgument::TemplateExpansion:
196 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000198 Y.getAsTemplateOrTemplatePattern()))
199 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000201 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000202 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000203
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000204 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205 // If we deduced a dependent expression in one case and either an integral
206 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207 // or declaration.
208 if (Y.getKind() == TemplateArgument::Integral ||
209 Y.getKind() == TemplateArgument::Declaration)
210 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
211 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213 if (Y.getKind() == TemplateArgument::Expression) {
214 // Compare the expressions for equality
215 llvm::FoldingSetNodeID ID1, ID2;
216 X.getAsExpr()->Profile(ID1, Context, true);
217 Y.getAsExpr()->Profile(ID2, Context, true);
218 if (ID1 == ID2)
219 return X;
220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000222 // All other combinations are incompatible.
223 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000225 case TemplateArgument::Declaration:
226 // If we deduced a declaration and a dependent expression, keep the
227 // declaration.
228 if (Y.getKind() == TemplateArgument::Expression)
229 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000231 // If we deduced a declaration and an integral constant, keep the
232 // integral constant.
233 if (Y.getKind() == TemplateArgument::Integral)
234 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000235
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000236 // If we deduced two declarations, make sure they they refer to the
237 // same declaration.
238 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000239 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000240 return X;
241
242 // All other combinations are incompatible.
243 return DeducedTemplateArgument();
244
245 case TemplateArgument::NullPtr:
246 // If we deduced a null pointer and a dependent expression, keep the
247 // null pointer.
248 if (Y.getKind() == TemplateArgument::Expression)
249 return X;
250
251 // If we deduced a null pointer and an integral constant, keep the
252 // integral constant.
253 if (Y.getKind() == TemplateArgument::Integral)
254 return Y;
255
256 // If we deduced two null pointers, make sure they have the same type.
257 if (Y.getKind() == TemplateArgument::NullPtr &&
258 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000261 // All other combinations are incompatible.
262 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000263
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000264 case TemplateArgument::Pack:
265 if (Y.getKind() != TemplateArgument::Pack ||
266 X.pack_size() != Y.pack_size())
267 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268
269 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000270 XAEnd = X.pack_end(),
271 YA = Y.pack_begin();
272 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000273 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 if (checkDeducedTemplateArguments(Context,
275 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000276 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
277 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000278 return DeducedTemplateArgument();
279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283
David Blaikiee4d798f2012-01-20 21:50:17 +0000284 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285}
286
Mike Stump11289f42009-09-09 15:08:12 +0000287/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000288/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000289static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000290DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000291 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000292 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000293 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000294 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000296 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000297 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000298
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000299 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
300 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 Deduced[NTTP->getIndex()],
303 NewDeduced);
304 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000305 Info.Param = NTTP;
306 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000312 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000313}
314
Mike Stump11289f42009-09-09 15:08:12 +0000315/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000316/// from the given type- or value-dependent expression.
317///
318/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000319static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000320DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000321 NonTypeTemplateParmDecl *NTTP,
322 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000323 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000325 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000326 "Cannot deduce non-type template argument with depth > 0");
327 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
328 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000330 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
332 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 if (Result.isNull()) {
336 Info.Param = NTTP;
337 Info.FirstArg = Deduced[NTTP->getIndex()];
338 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000343 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000344}
345
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000346/// \brief Deduce the value of the given non-type template parameter
347/// from the given declaration.
348///
349/// \returns true if deduction succeeded, false otherwise.
350static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000351DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000352 NonTypeTemplateParmDecl *NTTP,
353 ValueDecl *D,
354 TemplateDeductionInfo &Info,
355 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000356 assert(NTTP->getDepth() == 0 &&
357 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358
Craig Topperc3ec1492014-05-26 06:22:03 +0000359 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000360 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000361 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000363 Deduced[NTTP->getIndex()],
364 NewDeduced);
365 if (Result.isNull()) {
366 Info.Param = NTTP;
367 Info.FirstArg = Deduced[NTTP->getIndex()];
368 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000372 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000373 return Sema::TDK_Success;
374}
375
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000378 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000379 TemplateName Param,
380 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000381 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000383 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000384 if (!ParamDecl) {
385 // The parameter type is dependent and is not a template template parameter,
386 // so there is nothing that we can deduce.
387 return Sema::TDK_Success;
388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregoradee3e32009-11-11 23:06:43 +0000390 if (TemplateTemplateParmDecl *TempParam
391 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000392 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000394 Deduced[TempParam->getIndex()],
395 NewDeduced);
396 if (Result.isNull()) {
397 Info.Param = TempParam;
398 Info.FirstArg = Deduced[TempParam->getIndex()];
399 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000403 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406
Douglas Gregoradee3e32009-11-11 23:06:43 +0000407 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000408 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000409 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 // Mismatch of non-dependent template parameter to argument.
412 Info.FirstArg = TemplateArgument(Param);
413 Info.SecondArg = TemplateArgument(Arg);
414 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000415}
416
Mike Stump11289f42009-09-09 15:08:12 +0000417/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000418/// type (which is a template-id) with the template argument type.
419///
Chandler Carruthc1263112010-02-07 21:33:28 +0000420/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000421///
422/// \param TemplateParams the template parameters that we are deducing
423///
424/// \param Param the parameter type
425///
426/// \param Arg the argument type
427///
428/// \param Info information about the template argument deduction itself
429///
430/// \param Deduced the deduced template arguments
431///
432/// \returns the result of template argument deduction so far. Note that a
433/// "success" result means that template argument deduction has not yet failed,
434/// but it may still fail, later, for other reasons.
435static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000436DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000437 TemplateParameterList *TemplateParams,
438 const TemplateSpecializationType *Param,
439 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000440 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000441 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000442 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000445 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000446 = dyn_cast<TemplateSpecializationType>(Arg)) {
447 // Perform template argument deduction for the template name.
448 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000449 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000450 Param->getTemplateName(),
451 SpecArg->getTemplateName(),
452 Info, Deduced))
453 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000454
Mike Stump11289f42009-09-09 15:08:12 +0000455
Douglas Gregore81f3e72009-07-07 23:09:34 +0000456 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000457 // argument. Ignore any missing/extra arguments, since they could be
458 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459 return DeduceTemplateArguments(S, TemplateParams,
460 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000461 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000462 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregore81f3e72009-07-07 23:09:34 +0000465 // If the argument type is a class template specialization, we
466 // perform template argument deduction using its template
467 // arguments.
468 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000469 if (!RecordArg) {
470 Info.FirstArg = TemplateArgument(QualType(Param, 0));
471 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
475 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000476 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000477 if (!SpecArg) {
478 Info.FirstArg = TemplateArgument(QualType(Param, 0));
479 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 // Perform template argument deduction for the template name.
484 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000485 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000486 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000487 Param->getTemplateName(),
488 TemplateName(SpecArg->getSpecializedTemplate()),
489 Info, Deduced))
490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregor7baabef2010-12-22 18:17:10 +0000492 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000494 Param->getArgs(), Param->getNumArgs(),
495 SpecArg->getTemplateArgs().data(),
496 SpecArg->getTemplateArgs().size(),
497 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498}
499
John McCall08569062010-08-28 22:14:41 +0000500/// \brief Determines whether the given type is an opaque type that
501/// might be more qualified when instantiated.
502static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
503 switch (T->getTypeClass()) {
504 case Type::TypeOfExpr:
505 case Type::TypeOf:
506 case Type::DependentName:
507 case Type::Decltype:
508 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000509 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000510 return true;
511
512 case Type::ConstantArray:
513 case Type::IncompleteArray:
514 case Type::VariableArray:
515 case Type::DependentSizedArray:
516 return IsPossiblyOpaquelyQualifiedType(
517 cast<ArrayType>(T)->getElementType());
518
519 default:
520 return false;
521 }
522}
523
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000524/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000526getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000527 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
528 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Douglas Gregor5499af42011-01-05 23:12:31 +0000530 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
531 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532
Douglas Gregor5499af42011-01-05 23:12:31 +0000533 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
534 return std::make_pair(TTP->getDepth(), TTP->getIndex());
535}
536
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000537/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000539getDepthAndIndex(UnexpandedParameterPack UPP) {
540 if (const TemplateTypeParmType *TTP
541 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
542 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000544 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
545}
546
Douglas Gregor5499af42011-01-05 23:12:31 +0000547/// \brief Helper function to build a TemplateParameter when we don't
548/// know its type statically.
549static TemplateParameter makeTemplateParameter(Decl *D) {
550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
551 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor5499af42011-01-05 23:12:31 +0000555 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
556}
557
Richard Smith0a80d572014-05-29 01:12:14 +0000558/// A pack that we're currently deducing.
559struct clang::DeducedPack {
560 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000561
Richard Smith0a80d572014-05-29 01:12:14 +0000562 // The index of the pack.
563 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Richard Smith0a80d572014-05-29 01:12:14 +0000565 // The old value of the pack before we started deducing it.
566 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000567
Richard Smith0a80d572014-05-29 01:12:14 +0000568 // A deferred value of this pack from an inner deduction, that couldn't be
569 // deduced because this deduction hadn't happened yet.
570 DeducedTemplateArgument DeferredDeduction;
571
572 // The new value of the pack.
573 SmallVector<DeducedTemplateArgument, 4> New;
574
575 // The outer deduction for this pack, if any.
576 DeducedPack *Outer;
577};
578
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000579namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000580/// A scope in which we're performing pack deduction.
581class PackDeductionScope {
582public:
583 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
584 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
585 TemplateDeductionInfo &Info, TemplateArgument Pattern)
586 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
587 // Compute the set of template parameter indices that correspond to
588 // parameter packs expanded by the pack expansion.
589 {
590 llvm::SmallBitVector SawIndices(TemplateParams->size());
591 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
592 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
593 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
594 unsigned Depth, Index;
595 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
596 if (Depth == 0 && !SawIndices[Index]) {
597 SawIndices[Index] = true;
598
599 // Save the deduced template argument for the parameter pack expanded
600 // by this pack expansion, then clear out the deduction.
601 DeducedPack Pack(Index);
602 Pack.Saved = Deduced[Index];
603 Deduced[Index] = TemplateArgument();
604
605 Packs.push_back(Pack);
606 }
607 }
608 }
609 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
610
611 for (auto &Pack : Packs) {
612 if (Info.PendingDeducedPacks.size() > Pack.Index)
613 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
614 else
615 Info.PendingDeducedPacks.resize(Pack.Index + 1);
616 Info.PendingDeducedPacks[Pack.Index] = &Pack;
617
618 if (S.CurrentInstantiationScope) {
619 // If the template argument pack was explicitly specified, add that to
620 // the set of deduced arguments.
621 const TemplateArgument *ExplicitArgs;
622 unsigned NumExplicitArgs;
623 NamedDecl *PartiallySubstitutedPack =
624 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
625 &ExplicitArgs, &NumExplicitArgs);
626 if (PartiallySubstitutedPack &&
627 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
628 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
629 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000630 }
631 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000632
Richard Smith0a80d572014-05-29 01:12:14 +0000633 ~PackDeductionScope() {
634 for (auto &Pack : Packs)
635 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Richard Smith0a80d572014-05-29 01:12:14 +0000638 /// Move to deducing the next element in each pack that is being deduced.
639 void nextPackElement() {
640 // Capture the deduced template arguments for each parameter pack expanded
641 // by this pack expansion, add them to the list of arguments we've deduced
642 // for that pack, then clear out the deduced argument.
643 for (auto &Pack : Packs) {
644 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
645 if (!DeducedArg.isNull()) {
646 Pack.New.push_back(DeducedArg);
647 DeducedArg = DeducedTemplateArgument();
648 }
649 }
650 }
651
652 /// \brief Finish template argument deduction for a set of argument packs,
653 /// producing the argument packs and checking for consistency with prior
654 /// deductions.
655 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
656 // Build argument packs for each of the parameter packs expanded by this
657 // pack expansion.
658 for (auto &Pack : Packs) {
659 // Put back the old value for this pack.
660 Deduced[Pack.Index] = Pack.Saved;
661
662 // Build or find a new value for this pack.
663 DeducedTemplateArgument NewPack;
664 if (HasAnyArguments && Pack.New.empty()) {
665 if (Pack.DeferredDeduction.isNull()) {
666 // We were not able to deduce anything for this parameter pack
667 // (because it only appeared in non-deduced contexts), so just
668 // restore the saved argument pack.
669 continue;
670 }
671
672 NewPack = Pack.DeferredDeduction;
673 Pack.DeferredDeduction = TemplateArgument();
674 } else if (Pack.New.empty()) {
675 // If we deduced an empty argument pack, create it now.
676 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
677 } else {
678 TemplateArgument *ArgumentPack =
679 new (S.Context) TemplateArgument[Pack.New.size()];
680 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
681 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000682 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000683 Pack.New[0].wasDeducedFromArrayBound());
684 }
685
686 // Pick where we're going to put the merged pack.
687 DeducedTemplateArgument *Loc;
688 if (Pack.Outer) {
689 if (Pack.Outer->DeferredDeduction.isNull()) {
690 // Defer checking this pack until we have a complete pack to compare
691 // it against.
692 Pack.Outer->DeferredDeduction = NewPack;
693 continue;
694 }
695 Loc = &Pack.Outer->DeferredDeduction;
696 } else {
697 Loc = &Deduced[Pack.Index];
698 }
699
700 // Check the new pack matches any previous value.
701 DeducedTemplateArgument OldPack = *Loc;
702 DeducedTemplateArgument Result =
703 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
704
705 // If we deferred a deduction of this pack, check that one now too.
706 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
707 OldPack = Result;
708 NewPack = Pack.DeferredDeduction;
709 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
710 }
711
712 if (Result.isNull()) {
713 Info.Param =
714 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
715 Info.FirstArg = OldPack;
716 Info.SecondArg = NewPack;
717 return Sema::TDK_Inconsistent;
718 }
719
720 *Loc = Result;
721 }
722
723 return Sema::TDK_Success;
724 }
725
726private:
727 Sema &S;
728 TemplateParameterList *TemplateParams;
729 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
730 TemplateDeductionInfo &Info;
731
732 SmallVector<DeducedPack, 2> Packs;
733};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000734} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000735
Douglas Gregor5499af42011-01-05 23:12:31 +0000736/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737/// types to the list of argument types, as in the parameter-type-lists of
738/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000739///
740/// \param S The semantic analysis object within which we are deducing
741///
742/// \param TemplateParams The template parameters that we are deducing
743///
744/// \param Params The list of parameter types
745///
746/// \param NumParams The number of types in \c Params
747///
748/// \param Args The list of argument types
749///
750/// \param NumArgs The number of types in \c Args
751///
752/// \param Info information about the template argument deduction itself
753///
754/// \param Deduced the deduced template arguments
755///
756/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
757/// how template argument deduction is performed.
758///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000759/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000761/// (C++0x [temp.deduct.partial]).
762///
Douglas Gregor5499af42011-01-05 23:12:31 +0000763/// \returns the result of template argument deduction so far. Note that a
764/// "success" result means that template argument deduction has not yet failed,
765/// but it may still fail, later, for other reasons.
766static Sema::TemplateDeductionResult
767DeduceTemplateArguments(Sema &S,
768 TemplateParameterList *TemplateParams,
769 const QualType *Params, unsigned NumParams,
770 const QualType *Args, unsigned NumArgs,
771 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000772 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000773 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000774 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000775 // Fast-path check to see if we have too many/too few arguments.
776 if (NumParams != NumArgs &&
777 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
778 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000779 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
Douglas Gregor5499af42011-01-05 23:12:31 +0000781 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 // Similarly, if P has a form that contains (T), then each parameter type
783 // Pi of the respective parameter-type- list of P is compared with the
784 // corresponding parameter type Ai of the corresponding parameter-type-list
785 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000786 unsigned ArgIdx = 0, ParamIdx = 0;
787 for (; ParamIdx != NumParams; ++ParamIdx) {
788 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000790 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
791 if (!Expansion) {
792 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregor5499af42011-01-05 23:12:31 +0000794 // Make sure we have an argument.
795 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000796 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000798 if (isa<PackExpansionType>(Args[ArgIdx])) {
799 // C++0x [temp.deduct.type]p22:
800 // If the original function parameter associated with A is a function
801 // parameter pack and the function parameter associated with P is not
802 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000803 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor5499af42011-01-05 23:12:31 +0000806 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000807 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
808 Params[ParamIdx], Args[ArgIdx],
809 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000810 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
Douglas Gregor5499af42011-01-05 23:12:31 +0000813 ++ArgIdx;
814 continue;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000817 // C++0x [temp.deduct.type]p5:
818 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000820 // parameter-declaration-clause.
821 if (ParamIdx + 1 < NumParams)
822 return Sema::TDK_Success;
823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000826 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 // comparison deduces template arguments for subsequent positions in the
829 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000832 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833
Douglas Gregor5499af42011-01-05 23:12:31 +0000834 bool HasAnyArguments = false;
835 for (; ArgIdx < NumArgs; ++ArgIdx) {
836 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor5499af42011-01-05 23:12:31 +0000838 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000840 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
841 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000842 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Richard Smith0a80d572014-05-29 01:12:14 +0000845 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 // Build argument packs for each of the parameter packs expanded by this
849 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000850 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // Make sure we don't have any extra arguments.
855 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000856 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 return Sema::TDK_Success;
859}
860
Douglas Gregor1d684c22011-04-28 00:56:09 +0000861/// \brief Determine whether the parameter has qualifiers that are either
862/// inconsistent with or a superset of the argument's qualifiers.
863static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
864 QualType ArgType) {
865 Qualifiers ParamQs = ParamType.getQualifiers();
866 Qualifiers ArgQs = ArgType.getQualifiers();
867
868 if (ParamQs == ArgQs)
869 return false;
870
871 // Mismatched (but not missing) Objective-C GC attributes.
872 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
873 ParamQs.hasObjCGCAttr())
874 return true;
875
876 // Mismatched (but not missing) address spaces.
877 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
878 ParamQs.hasAddressSpace())
879 return true;
880
John McCall31168b02011-06-15 23:02:42 +0000881 // Mismatched (but not missing) Objective-C lifetime qualifiers.
882 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
883 ParamQs.hasObjCLifetime())
884 return true;
885
Douglas Gregor1d684c22011-04-28 00:56:09 +0000886 // CVR qualifier superset.
887 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
888 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
889 == ParamQs.getCVRQualifiers());
890}
891
Douglas Gregor19a41f12013-04-17 08:45:07 +0000892/// \brief Compare types for equality with respect to possibly compatible
893/// function types (noreturn adjustment, implicit calling conventions). If any
894/// of parameter and argument is not a function, just perform type comparison.
895///
896/// \param Param the template parameter type.
897///
898/// \param Arg the argument type.
899bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
900 CanQualType Arg) {
901 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
902 *ArgFunction = Arg->getAs<FunctionType>();
903
904 // Just compare if not functions.
905 if (!ParamFunction || !ArgFunction)
906 return Param == Arg;
907
908 // Noreturn adjustment.
909 QualType AdjustedParam;
910 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
911 return Arg == Context.getCanonicalType(AdjustedParam);
912
913 // FIXME: Compatible calling conventions.
914
915 return Param == Arg;
916}
917
Douglas Gregorcceb9752009-06-26 18:27:22 +0000918/// \brief Deduce the template arguments by comparing the parameter type and
919/// the argument type (C++ [temp.deduct.type]).
920///
Chandler Carruthc1263112010-02-07 21:33:28 +0000921/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000922///
923/// \param TemplateParams the template parameters that we are deducing
924///
925/// \param ParamIn the parameter type
926///
927/// \param ArgIn the argument type
928///
929/// \param Info information about the template argument deduction itself
930///
931/// \param Deduced the deduced template arguments
932///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000933/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000934/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000935///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000936/// \param PartialOrdering Whether we're performing template argument deduction
937/// in the context of partial ordering (C++0x [temp.deduct.partial]).
938///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000939/// \returns the result of template argument deduction so far. Note that a
940/// "success" result means that template argument deduction has not yet failed,
941/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000942static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000943DeduceTemplateArgumentsByTypeMatch(Sema &S,
944 TemplateParameterList *TemplateParams,
945 QualType ParamIn, QualType ArgIn,
946 TemplateDeductionInfo &Info,
947 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
948 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000949 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000950 // We only want to look at the canonical types, since typedefs and
951 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000952 QualType Param = S.Context.getCanonicalType(ParamIn);
953 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000954
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000955 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000957 if (const PackExpansionType *ArgExpansion
958 = dyn_cast<PackExpansionType>(Arg))
959 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Douglas Gregorb837ea42011-01-11 17:34:58 +0000961 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000962 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963 // Before the partial ordering is done, certain transformations are
964 // performed on the types used for partial ordering:
965 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000966 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
967 if (ParamRef)
968 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorb837ea42011-01-11 17:34:58 +0000970 // - If A is a reference type, A is replaced by the type referred to.
971 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
972 if (ArgRef)
973 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
Richard Smithed563c22015-02-20 04:45:22 +0000975 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
976 // C++11 [temp.deduct.partial]p9:
977 // If, for a given type, deduction succeeds in both directions (i.e.,
978 // the types are identical after the transformations above) and both
979 // P and A were reference types [...]:
980 // - if [one type] was an lvalue reference and [the other type] was
981 // not, [the other type] is not considered to be at least as
982 // specialized as [the first type]
983 // - if [one type] is more cv-qualified than [the other type],
984 // [the other type] is not considered to be at least as specialized
985 // as [the first type]
986 // Objective-C ARC adds:
987 // - [one type] has non-trivial lifetime, [the other type] has
988 // __unsafe_unretained lifetime, and the types are otherwise
989 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +0000990 //
Richard Smithed563c22015-02-20 04:45:22 +0000991 // A is "considered to be at least as specialized" as P iff deduction
992 // succeeds, so we model this as a deduction failure. Note that
993 // [the first type] is P and [the other type] is A here; the standard
994 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +0000995 Qualifiers ParamQuals = Param.getQualifiers();
996 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +0000997 if ((ParamRef->isLValueReferenceType() &&
998 !ArgRef->isLValueReferenceType()) ||
999 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1000 (ParamQuals.hasNonTrivialObjCLifetime() &&
1001 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1002 ParamQuals.withoutObjCLifetime() ==
1003 ArgQuals.withoutObjCLifetime())) {
1004 Info.FirstArg = TemplateArgument(ParamIn);
1005 Info.SecondArg = TemplateArgument(ArgIn);
1006 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001007 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Richard Smithed563c22015-02-20 04:45:22 +00001010 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001011 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // version of P.
1014 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001016 // version of A.
1017 Arg = Arg.getUnqualifiedType();
1018 } else {
1019 // C++0x [temp.deduct.call]p4 bullet 1:
1020 // - If the original P is a reference type, the deduced A (i.e., the type
1021 // referred to by the reference) can be more cv-qualified than the
1022 // transformed A.
1023 if (TDF & TDF_ParamWithReferenceType) {
1024 Qualifiers Quals;
1025 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1026 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001027 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001028 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Douglas Gregor85f240c2011-01-25 17:19:08 +00001031 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1032 // C++0x [temp.deduct.type]p10:
1033 // If P and A are function types that originated from deduction when
1034 // taking the address of a function template (14.8.2.2) or when deducing
1035 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036 // Ai are parameters of the top-level parameter-type-list of P and A,
1037 // respectively, Pi is adjusted if it is an rvalue reference to a
1038 // cv-unqualified template parameter and Ai is an lvalue reference, in
1039 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001040 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1041 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001042 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001043 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregor85f240c2011-01-25 17:19:08 +00001045 if (const RValueReferenceType *ParamRef
1046 = Param->getAs<RValueReferenceType>()) {
1047 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1048 !ParamRef->getPointeeType().getQualifiers())
1049 if (Arg->isLValueReferenceType())
1050 Param = ParamRef->getPointeeType();
1051 }
1052 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001055 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001056 // A template type argument T, a template template argument TT or a
1057 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001058 // the following forms:
1059 //
1060 // T
1061 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001062 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001063 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001064 // Just skip any attempts to deduce from a placeholder type.
1065 if (Arg->isPlaceholderType())
1066 return Sema::TDK_Success;
1067
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001068 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001069 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregor60454822009-07-22 20:02:25 +00001071 // If the argument type is an array type, move the qualifiers up to the
1072 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001073 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001074 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001075 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001076 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001077 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001078 RecanonicalizeArg = true;
1079 }
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001082 // The argument type can not be less qualified than the parameter
1083 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001084 if (!(TDF & TDF_IgnoreQualifiers) &&
1085 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001086 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001087 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001088 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001089 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001090 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001091
1092 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001093 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001094 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001095
Douglas Gregor1d684c22011-04-28 00:56:09 +00001096 // Remove any qualifiers on the parameter from the deduced type.
1097 // We checked the qualifiers for consistency above.
1098 Qualifiers DeducedQs = DeducedType.getQualifiers();
1099 Qualifiers ParamQs = Param.getQualifiers();
1100 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1101 if (ParamQs.hasObjCGCAttr())
1102 DeducedQs.removeObjCGCAttr();
1103 if (ParamQs.hasAddressSpace())
1104 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001105 if (ParamQs.hasObjCLifetime())
1106 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001107
1108 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001109 // If template deduction would produce a lifetime qualifier on a type
1110 // that is not a lifetime type, template argument deduction fails.
1111 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1112 !DeducedType->isDependentType()) {
1113 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1114 Info.FirstArg = TemplateArgument(Param);
1115 Info.SecondArg = TemplateArgument(Arg);
1116 return Sema::TDK_Underqualified;
1117 }
1118
1119 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001120 // If template deduction would produce an argument type with lifetime type
1121 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001123 DeducedType->isObjCLifetimeType() &&
1124 !DeducedQs.hasObjCLifetime())
1125 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1126
Douglas Gregor1d684c22011-04-28 00:56:09 +00001127 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1128 DeducedQs);
1129
Douglas Gregord6605db2009-07-22 21:30:48 +00001130 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001131 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001133 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001135 Deduced[Index],
1136 NewDeduced);
1137 if (Result.isNull()) {
1138 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1139 Info.FirstArg = Deduced[Index];
1140 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001144 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001146 }
1147
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001148 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001149 Info.FirstArg = TemplateArgument(ParamIn);
1150 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001151
Douglas Gregorfb322d82011-01-14 05:11:40 +00001152 // If the parameter is an already-substituted template parameter
1153 // pack, do nothing: we don't know which of its arguments to look
1154 // at, so we have to wait until all of the parameter packs in this
1155 // expansion have arguments.
1156 if (isa<SubstTemplateTypeParmPackType>(Param))
1157 return Sema::TDK_Success;
1158
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001159 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001160 CanQualType CanParam = S.Context.getCanonicalType(Param);
1161 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001162 if (!(TDF & TDF_IgnoreQualifiers)) {
1163 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001164 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001165 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001166 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001167 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001168 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001169 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001170
1171 // If the parameter type is not dependent, there is nothing to deduce.
1172 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001173 if (!(TDF & TDF_SkipNonDependent)) {
1174 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1175 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1176 Param != Arg;
1177 if (NonDeduced) {
1178 return Sema::TDK_NonDeducedMismatch;
1179 }
1180 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001181 return Sema::TDK_Success;
1182 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001183 } else if (!Param->isDependentType()) {
1184 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1185 ArgUnqualType = CanArg.getUnqualifiedType();
1186 bool Success = (TDF & TDF_InOverloadResolution)?
1187 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1188 ArgUnqualType) :
1189 ParamUnqualType == ArgUnqualType;
1190 if (Success)
1191 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001192 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001193
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001194 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001195 // Non-canonical types cannot appear here.
1196#define NON_CANONICAL_TYPE(Class, Base) \
1197 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1198#define TYPE(Class, Base)
1199#include "clang/AST/TypeNodes.def"
1200
1201 case Type::TemplateTypeParm:
1202 case Type::SubstTemplateTypeParmPack:
1203 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001204
1205 // These types cannot be dependent, so simply check whether the types are
1206 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001207 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001208 case Type::VariableArray:
1209 case Type::Vector:
1210 case Type::FunctionNoProto:
1211 case Type::Record:
1212 case Type::Enum:
1213 case Type::ObjCObject:
1214 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001215 case Type::ObjCObjectPointer: {
1216 if (TDF & TDF_SkipNonDependent)
1217 return Sema::TDK_Success;
1218
1219 if (TDF & TDF_IgnoreQualifiers) {
1220 Param = Param.getUnqualifiedType();
1221 Arg = Arg.getUnqualifiedType();
1222 }
1223
1224 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1225 }
1226
Douglas Gregor39c02722011-06-15 16:02:29 +00001227 // _Complex T [placeholder extension]
1228 case Type::Complex:
1229 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001230 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001232 ComplexArg->getElementType(),
1233 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001234
1235 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001236
1237 // _Atomic T [extension]
1238 case Type::Atomic:
1239 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001240 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001241 cast<AtomicType>(Param)->getValueType(),
1242 AtomicArg->getValueType(),
1243 Info, Deduced, TDF);
1244
1245 return Sema::TDK_NonDeducedMismatch;
1246
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001247 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001248 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001249 QualType PointeeType;
1250 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1251 PointeeType = PointerArg->getPointeeType();
1252 } else if (const ObjCObjectPointerType *PointerArg
1253 = Arg->getAs<ObjCObjectPointerType>()) {
1254 PointeeType = PointerArg->getPointeeType();
1255 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001256 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregorfc516c92009-06-26 23:27:24 +00001259 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001260 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1261 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001262 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001263 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001266 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001267 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001268 const LValueReferenceType *ReferenceArg =
1269 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001270 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001271 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001273 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001274 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001275 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001276 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001277
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001278 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001279 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001280 const RValueReferenceType *ReferenceArg =
1281 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001282 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001283 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001285 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1286 cast<RValueReferenceType>(Param)->getPointeeType(),
1287 ReferenceArg->getPointeeType(),
1288 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001291 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001292 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001293 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001294 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001295 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001296 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCallf7332682010-08-19 00:20:19 +00001298 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1300 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1301 IncompleteArrayArg->getElementType(),
1302 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001303 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001304
1305 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001306 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001307 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001308 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001309 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001310 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001311
1312 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001313 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001314 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001315 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCallf7332682010-08-19 00:20:19 +00001317 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001318 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1319 ConstantArrayParm->getElementType(),
1320 ConstantArrayArg->getElementType(),
1321 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001322 }
1323
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 // type [i]
1325 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001326 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001328 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCallf7332682010-08-19 00:20:19 +00001330 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1331
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001332 // Check the element type of the arrays
1333 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001334 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1337 DependentArrayParm->getElementType(),
1338 ArrayArg->getElementType(),
1339 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001340 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001343 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001344 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1345 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001349 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001350 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001351 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001352 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001353 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1354 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001356 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001357 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001358 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001359 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 if (const DependentSizedArrayType *DependentArrayArg
1361 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001362 if (DependentArrayArg->getSizeExpr())
1363 return DeduceNonTypeTemplateArgument(S, NTTP,
1364 DependentArrayArg->getSizeExpr(),
1365 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001368 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
1371 // type(*)(T)
1372 // T(*)()
1373 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001374 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001375 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001376 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001377 dyn_cast<FunctionProtoType>(Arg);
1378 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001379 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001380
1381 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001382 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001385 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001387 != FunctionProtoArg->getRefQualifier() ||
1388 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001389 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001390
Anders Carlsson2128ec72009-06-08 15:19:08 +00001391 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001392 if (Sema::TemplateDeductionResult Result =
1393 DeduceTemplateArgumentsByTypeMatch(
1394 S, TemplateParams, FunctionProtoParam->getReturnType(),
1395 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Alp Toker9cacbab2014-01-20 20:26:09 +00001398 return DeduceTemplateArguments(
1399 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1400 FunctionProtoParam->getNumParams(),
1401 FunctionProtoArg->param_type_begin(),
1402 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCalle78aac42010-03-10 03:28:59 +00001405 case Type::InjectedClassName: {
1406 // Treat a template's injected-class-name as if the template
1407 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001408 Param = cast<InjectedClassNameType>(Param)
1409 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001410 assert(isa<TemplateSpecializationType>(Param) &&
1411 "injected class name is not a template specialization type");
1412 // fall through
1413 }
1414
Douglas Gregor705c9002009-06-26 20:57:09 +00001415 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001416 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001417 // TT<T>
1418 // TT<i>
1419 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001420 case Type::TemplateSpecialization: {
1421 const TemplateSpecializationType *SpecParam
1422 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregore81f3e72009-07-07 23:09:34 +00001424 // Try to deduce template arguments from the template-id.
1425 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001426 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001427 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Douglas Gregor42909752009-09-30 22:13:51 +00001429 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001430 // C++ [temp.deduct.call]p3b3:
1431 // If P is a class, and P has the form template-id, then A can be a
1432 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001433 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001434 // class pointed to by the deduced A.
1435 //
1436 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001437 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001438 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001439 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1440 // We cannot inspect base classes as part of deduction when the type
1441 // is incomplete, so either instantiate any templates necessary to
1442 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001443 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001444 return Result;
1445
Douglas Gregore81f3e72009-07-07 23:09:34 +00001446 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001447 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001448 // ToVisit is our stack of records that we still need to visit.
1449 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001450 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001451 ToVisit.push_back(RecordT);
1452 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001453 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001455 while (!ToVisit.empty()) {
1456 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001457 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregore81f3e72009-07-07 23:09:34 +00001459 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001460 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001461 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregore81f3e72009-07-07 23:09:34 +00001463 // If this is a base class, try to perform template argument
1464 // deduction from it.
1465 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001466 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001467 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001468 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001469 QualType(NextT, 0), BaseInfo,
1470 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Douglas Gregore81f3e72009-07-07 23:09:34 +00001472 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001473 // note that we had some success. Otherwise, ignore any deductions
1474 // from this base class.
1475 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001476 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001477 DeducedOrig.clear();
1478 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001479 Info.Param = BaseInfo.Param;
1480 Info.FirstArg = BaseInfo.FirstArg;
1481 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001482 }
1483 else
1484 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregore81f3e72009-07-07 23:09:34 +00001487 // Visit base classes
1488 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001489 for (const auto &Base : Next->bases()) {
1490 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001492 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001493 }
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Douglas Gregore81f3e72009-07-07 23:09:34 +00001496 if (Successful)
1497 return Sema::TDK_Success;
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregore81f3e72009-07-07 23:09:34 +00001500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregore81f3e72009-07-07 23:09:34 +00001502 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001503 }
1504
Douglas Gregor637d9982009-06-10 23:47:09 +00001505 // T type::*
1506 // T T::*
1507 // T (type::*)()
1508 // type (T::*)()
1509 // type (type::*)(T)
1510 // type (T::*)(T)
1511 // T (type::*)(T)
1512 // T (T::*)()
1513 // T (T::*)(T)
1514 case Type::MemberPointer: {
1515 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1516 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1517 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001518 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001519
David Majnemera381cda2015-11-30 20:34:28 +00001520 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1521 if (ParamPointeeType->isFunctionType())
1522 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1523 /*IsCtorOrDtor=*/false, Info.getLocation());
1524 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1525 if (ArgPointeeType->isFunctionType())
1526 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1527 /*IsCtorOrDtor=*/false, Info.getLocation());
1528
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001529 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001530 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001531 ParamPointeeType,
1532 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001533 Info, Deduced,
1534 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001535 return Result;
1536
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001537 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1538 QualType(MemPtrParam->getClass(), 0),
1539 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001540 Info, Deduced,
1541 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001542 }
1543
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001544 // (clang extension)
1545 //
Mike Stump11289f42009-09-09 15:08:12 +00001546 // type(^)(T)
1547 // T(^)()
1548 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001549 case Type::BlockPointer: {
1550 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1551 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anders Carlssona767eee2009-06-12 16:23:10 +00001553 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001554 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001555
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001556 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1557 BlockPtrParam->getPointeeType(),
1558 BlockPtrArg->getPointeeType(),
1559 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001560 }
1561
Douglas Gregor39c02722011-06-15 16:02:29 +00001562 // (clang extension)
1563 //
1564 // T __attribute__(((ext_vector_type(<integral constant>))))
1565 case Type::ExtVector: {
1566 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1567 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1568 // Make sure that the vectors have the same number of elements.
1569 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1570 return Sema::TDK_NonDeducedMismatch;
1571
1572 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001573 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1574 VectorParam->getElementType(),
1575 VectorArg->getElementType(),
1576 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001577 }
1578
1579 if (const DependentSizedExtVectorType *VectorArg
1580 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1581 // We can't check the number of elements, since the argument has a
1582 // dependent number of elements. This can only occur during partial
1583 // ordering.
1584
1585 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001586 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587 VectorParam->getElementType(),
1588 VectorArg->getElementType(),
1589 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001590 }
1591
1592 return Sema::TDK_NonDeducedMismatch;
1593 }
1594
1595 // (clang extension)
1596 //
1597 // T __attribute__(((ext_vector_type(N))))
1598 case Type::DependentSizedExtVector: {
1599 const DependentSizedExtVectorType *VectorParam
1600 = cast<DependentSizedExtVectorType>(Param);
1601
1602 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1603 // Perform deduction on the element types.
1604 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001605 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606 VectorParam->getElementType(),
1607 VectorArg->getElementType(),
1608 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001609 return Result;
1610
1611 // Perform deduction on the vector size, if we can.
1612 NonTypeTemplateParmDecl *NTTP
1613 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1614 if (!NTTP)
1615 return Sema::TDK_Success;
1616
1617 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1618 ArgSize = VectorArg->getNumElements();
1619 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1620 false, Info, Deduced);
1621 }
1622
1623 if (const DependentSizedExtVectorType *VectorArg
1624 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1625 // Perform deduction on the element types.
1626 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001627 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628 VectorParam->getElementType(),
1629 VectorArg->getElementType(),
1630 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001631 return Result;
1632
1633 // Perform deduction on the vector size, if we can.
1634 NonTypeTemplateParmDecl *NTTP
1635 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1636 if (!NTTP)
1637 return Sema::TDK_Success;
1638
1639 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1640 Info, Deduced);
1641 }
1642
1643 return Sema::TDK_NonDeducedMismatch;
1644 }
1645
Douglas Gregor637d9982009-06-10 23:47:09 +00001646 case Type::TypeOfExpr:
1647 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001648 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001649 case Type::UnresolvedUsing:
1650 case Type::Decltype:
1651 case Type::UnaryTransform:
1652 case Type::Auto:
1653 case Type::DependentTemplateSpecialization:
1654 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001655 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001656 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001657 }
1658
David Blaikiee4d798f2012-01-20 21:50:17 +00001659 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001660}
1661
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001662static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001663DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001664 TemplateParameterList *TemplateParams,
1665 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001666 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001667 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001668 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001669 // If the template argument is a pack expansion, perform template argument
1670 // deduction against the pattern of that expansion. This only occurs during
1671 // partial ordering.
1672 if (Arg.isPackExpansion())
1673 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001675 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001676 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001677 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001678
1679 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001680 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001681 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1682 Param.getAsType(),
1683 Arg.getAsType(),
1684 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001685 Info.FirstArg = Param;
1686 Info.SecondArg = Arg;
1687 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001688
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001689 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001690 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001692 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001693 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001694 Info.FirstArg = Param;
1695 Info.SecondArg = Arg;
1696 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001697
1698 case TemplateArgument::TemplateExpansion:
1699 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001701 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001702 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001703 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001704 return Sema::TDK_Success;
1705
1706 Info.FirstArg = Param;
1707 Info.SecondArg = Arg;
1708 return Sema::TDK_NonDeducedMismatch;
1709
1710 case TemplateArgument::NullPtr:
1711 if (Arg.getKind() == TemplateArgument::NullPtr &&
1712 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001713 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001714
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001715 Info.FirstArg = Param;
1716 Info.SecondArg = Arg;
1717 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001719 case TemplateArgument::Integral:
1720 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001721 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001722 return Sema::TDK_Success;
1723
1724 Info.FirstArg = Param;
1725 Info.SecondArg = Arg;
1726 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001727 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001728
1729 if (Arg.getKind() == TemplateArgument::Expression) {
1730 Info.FirstArg = Param;
1731 Info.SecondArg = Arg;
1732 return Sema::TDK_NonDeducedMismatch;
1733 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001734
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001735 Info.FirstArg = Param;
1736 Info.SecondArg = Arg;
1737 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001739 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001740 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001741 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1742 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001743 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001744 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001745 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001746 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001747 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001748 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001749 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001750 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001751 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001752 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001753 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001754
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001755 Info.FirstArg = Param;
1756 Info.SecondArg = Arg;
1757 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001758 }
Mike Stump11289f42009-09-09 15:08:12 +00001759
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001760 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001761 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001762 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001763 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001764 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001765 }
Mike Stump11289f42009-09-09 15:08:12 +00001766
David Blaikiee4d798f2012-01-20 21:50:17 +00001767 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001768}
1769
Douglas Gregor7baabef2010-12-22 18:17:10 +00001770/// \brief Determine whether there is a template argument to be used for
1771/// deduction.
1772///
1773/// This routine "expands" argument packs in-place, overriding its input
1774/// parameters so that \c Args[ArgIdx] will be the available template argument.
1775///
1776/// \returns true if there is another template argument (which will be at
1777/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001779 unsigned &ArgIdx,
1780 unsigned &NumArgs) {
1781 if (ArgIdx == NumArgs)
1782 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783
Douglas Gregor7baabef2010-12-22 18:17:10 +00001784 const TemplateArgument &Arg = Args[ArgIdx];
1785 if (Arg.getKind() != TemplateArgument::Pack)
1786 return true;
1787
1788 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1789 Args = Arg.pack_begin();
1790 NumArgs = Arg.pack_size();
1791 ArgIdx = 0;
1792 return ArgIdx < NumArgs;
1793}
1794
Douglas Gregord0ad2942010-12-23 01:24:45 +00001795/// \brief Determine whether the given set of template arguments has a pack
1796/// expansion that is not the last template argument.
1797static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1798 unsigned NumArgs) {
1799 unsigned ArgIdx = 0;
1800 while (ArgIdx < NumArgs) {
1801 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802
Douglas Gregord0ad2942010-12-23 01:24:45 +00001803 // Unwrap argument packs.
1804 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1805 Args = Arg.pack_begin();
1806 NumArgs = Arg.pack_size();
1807 ArgIdx = 0;
1808 continue;
1809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregord0ad2942010-12-23 01:24:45 +00001811 ++ArgIdx;
1812 if (ArgIdx == NumArgs)
1813 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814
Douglas Gregord0ad2942010-12-23 01:24:45 +00001815 if (Arg.isPackExpansion())
1816 return true;
1817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Douglas Gregord0ad2942010-12-23 01:24:45 +00001819 return false;
1820}
1821
Douglas Gregor7baabef2010-12-22 18:17:10 +00001822static Sema::TemplateDeductionResult
1823DeduceTemplateArguments(Sema &S,
1824 TemplateParameterList *TemplateParams,
1825 const TemplateArgument *Params, unsigned NumParams,
1826 const TemplateArgument *Args, unsigned NumArgs,
1827 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001828 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001829 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830 // If the template argument list of P contains a pack expansion that is not
1831 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001832 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001833 if (hasPackExpansionBeforeEnd(Params, NumParams))
1834 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001835
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001836 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837 // If P has a form that contains <T> or <i>, then each argument Pi of the
1838 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001839 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001840 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001842 ++ParamIdx) {
1843 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001844 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregor7baabef2010-12-22 18:17:10 +00001846 // Check whether we have enough arguments.
1847 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001848 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001850 if (Args[ArgIdx].isPackExpansion()) {
1851 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1852 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001853 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001856 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001857 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001858 = DeduceTemplateArguments(S, TemplateParams,
1859 Params[ParamIdx], Args[ArgIdx],
1860 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001861 return Result;
1862
Douglas Gregor7baabef2010-12-22 18:17:10 +00001863 // Move to the next argument.
1864 ++ArgIdx;
1865 continue;
1866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001868 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001870 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001871 // If Pi is a pack expansion, then the pattern of Pi is compared with
1872 // each remaining argument in the template argument list of A. Each
1873 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001874 // template parameter packs expanded by Pi.
1875 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001877 // FIXME: If there are no remaining arguments, we can bail out early
1878 // and set any deduced parameter packs to an empty argument pack.
1879 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880
Richard Smith0a80d572014-05-29 01:12:14 +00001881 // Prepare to deduce the packs within the pattern.
1882 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001883
1884 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001886 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001888 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001889 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001893 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1894 Info, Deduced))
1895 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Richard Smith0a80d572014-05-29 01:12:14 +00001897 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001900 // Build argument packs for each of the parameter packs expanded by this
1901 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001902 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
Douglas Gregor7baabef2010-12-22 18:17:10 +00001906 return Sema::TDK_Success;
1907}
1908
Mike Stump11289f42009-09-09 15:08:12 +00001909static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001910DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001911 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001912 const TemplateArgumentList &ParamList,
1913 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001914 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001915 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001916 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001917 ParamList.data(), ParamList.size(),
1918 ArgList.data(), ArgList.size(),
1919 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001920}
1921
Douglas Gregor705c9002009-06-26 20:57:09 +00001922/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001923static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001924 const TemplateArgument &X,
1925 const TemplateArgument &Y) {
1926 if (X.getKind() != Y.getKind())
1927 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor705c9002009-06-26 20:57:09 +00001929 switch (X.getKind()) {
1930 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001931 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001932
Douglas Gregor705c9002009-06-26 20:57:09 +00001933 case TemplateArgument::Type:
1934 return Context.getCanonicalType(X.getAsType()) ==
1935 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001936
Douglas Gregor705c9002009-06-26 20:57:09 +00001937 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001938 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001939
1940 case TemplateArgument::NullPtr:
1941 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001942
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001943 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001944 case TemplateArgument::TemplateExpansion:
1945 return Context.getCanonicalTemplateName(
1946 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1947 Context.getCanonicalTemplateName(
1948 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Douglas Gregor705c9002009-06-26 20:57:09 +00001950 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001951 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001952
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001953 case TemplateArgument::Expression: {
1954 llvm::FoldingSetNodeID XID, YID;
1955 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001957 return XID == YID;
1958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor705c9002009-06-26 20:57:09 +00001960 case TemplateArgument::Pack:
1961 if (X.pack_size() != Y.pack_size())
1962 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001963
1964 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1965 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001966 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001967 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001968 if (!isSameTemplateArg(Context, *XP, *YP))
1969 return false;
1970
1971 return true;
1972 }
1973
David Blaikiee4d798f2012-01-20 21:50:17 +00001974 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001975}
1976
Douglas Gregorca4686d2011-01-04 23:35:54 +00001977/// \brief Allocate a TemplateArgumentLoc where all locations have
1978/// been initialized to the given location.
1979///
1980/// \param S The semantic analysis object.
1981///
James Dennett634962f2012-06-14 21:40:34 +00001982/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001983/// location information for.
1984///
1985/// \param NTTPType For a declaration template argument, the type of
1986/// the non-type template parameter that corresponds to this template
1987/// argument.
1988///
1989/// \param Loc The source location to use for the resulting template
1990/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001991static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00001992getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001994 QualType NTTPType,
1995 SourceLocation Loc) {
1996 switch (Arg.getKind()) {
1997 case TemplateArgument::Null:
1998 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999
Douglas Gregorca4686d2011-01-04 23:35:54 +00002000 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002002 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Douglas Gregorca4686d2011-01-04 23:35:54 +00002004 case TemplateArgument::Declaration: {
2005 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002006 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002007 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002008 return TemplateArgumentLoc(TemplateArgument(E), E);
2009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002010
Eli Friedmanb826a002012-09-26 02:36:12 +00002011 case TemplateArgument::NullPtr: {
2012 Expr *E
2013 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002014 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002015 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2016 E);
2017 }
2018
Douglas Gregorca4686d2011-01-04 23:35:54 +00002019 case TemplateArgument::Integral: {
2020 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002021 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002022 return TemplateArgumentLoc(TemplateArgument(E), E);
2023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregor9d802122011-03-02 17:09:35 +00002025 case TemplateArgument::Template:
2026 case TemplateArgument::TemplateExpansion: {
2027 NestedNameSpecifierLocBuilder Builder;
2028 TemplateName Template = Arg.getAsTemplate();
2029 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2030 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002031 else if (QualifiedTemplateName *QTN =
2032 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002033 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2034
2035 if (Arg.getKind() == TemplateArgument::Template)
2036 return TemplateArgumentLoc(Arg,
2037 Builder.getWithLocInContext(S.Context),
2038 Loc);
2039
2040
2041 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2042 Loc, Loc);
2043 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002044
Douglas Gregorca4686d2011-01-04 23:35:54 +00002045 case TemplateArgument::Expression:
2046 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregorca4686d2011-01-04 23:35:54 +00002048 case TemplateArgument::Pack:
2049 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051
David Blaikiee4d798f2012-01-20 21:50:17 +00002052 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002053}
2054
2055
2056/// \brief Convert the given deduced template argument and add it to the set of
2057/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002058static bool
2059ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2060 DeducedTemplateArgument Arg,
2061 NamedDecl *Template,
2062 QualType NTTPType,
2063 unsigned ArgumentPackIndex,
2064 TemplateDeductionInfo &Info,
2065 bool InFunctionTemplate,
2066 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002067 if (Arg.getKind() == TemplateArgument::Pack) {
2068 // This is a template argument pack, so check each of its arguments against
2069 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002070 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002071 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002072 // When converting the deduced template argument, append it to the
2073 // general output list. We need to do this so that the template argument
2074 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002075 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002078 NTTPType, PackedArgsBuilder.size(),
2079 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregor51bc5712011-01-05 20:52:18 +00002082 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002083 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Douglas Gregorca4686d2011-01-04 23:35:54 +00002086 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002087 Output.push_back(
2088 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002089 return false;
2090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091
Douglas Gregorca4686d2011-01-04 23:35:54 +00002092 // Convert the deduced template argument into a template
2093 // argument that we can check, almost as if the user had written
2094 // the template argument explicitly.
2095 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2096 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Douglas Gregorca4686d2011-01-04 23:35:54 +00002098 // Check the template argument, converting it as necessary.
2099 return S.CheckTemplateArgument(Param, ArgLoc,
2100 Template,
2101 Template->getLocation(),
2102 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002103 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002104 Output,
2105 InFunctionTemplate
2106 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002108 : Sema::CTAK_Deduced)
2109 : Sema::CTAK_Specified);
2110}
2111
Douglas Gregor684268d2010-04-29 06:21:43 +00002112/// Complete template argument deduction for a class template partial
2113/// specialization.
2114static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002116 ClassTemplatePartialSpecializationDecl *Partial,
2117 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002118 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002119 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002120 // Unevaluated SFINAE context.
2121 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002122 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
Douglas Gregor684268d2010-04-29 06:21:43 +00002124 Sema::ContextRAII SavedContext(S, Partial);
2125
2126 // C++ [temp.deduct.type]p2:
2127 // [...] or if any template argument remains neither deduced nor
2128 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002129 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002130 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2131 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002132 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002133 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002134 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002135 return Sema::TDK_Incomplete;
2136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
Douglas Gregorca4686d2011-01-04 23:35:54 +00002138 // We have deduced this argument, so it still needs to be
2139 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002140
Douglas Gregorca4686d2011-01-04 23:35:54 +00002141 // First, for a non-type template parameter type that is
2142 // initialized by a declaration, we need the type of the
2143 // corresponding non-type template parameter.
2144 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002146 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002147 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002148 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002150 Builder.data(), Builder.size());
2151 NTTPType = S.SubstType(NTTPType,
2152 MultiLevelTemplateArgumentList(TemplateArgs),
2153 NTTP->getLocation(),
2154 NTTP->getDeclName());
2155 if (NTTPType.isNull()) {
2156 Info.Param = makeTemplateParameter(Param);
2157 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2159 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002160 Builder.size()));
2161 return Sema::TDK_SubstitutionFailure;
2162 }
2163 }
2164 }
2165
Douglas Gregorca4686d2011-01-04 23:35:54 +00002166 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002167 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002168 Builder)) {
2169 Info.Param = makeTemplateParameter(Param);
2170 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2172 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002173 return Sema::TDK_SubstitutionFailure;
2174 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002175 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregor684268d2010-04-29 06:21:43 +00002177 // Form the template argument list from the deduced template arguments.
2178 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002180 Builder.size());
2181
Douglas Gregor684268d2010-04-29 06:21:43 +00002182 Info.reset(DeducedArgumentList);
2183
2184 // Substitute the deduced template arguments into the template
2185 // arguments of the class template partial specialization, and
2186 // verify that the instantiated template arguments are both valid
2187 // and are equivalent to the template arguments originally provided
2188 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002189 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002190 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002191 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002192 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002193 const TemplateArgumentLoc *PartialTemplateArgs
2194 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002195
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002196 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2197 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002198
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002199 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002200 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2201 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2202 if (ParamIdx >= Partial->getTemplateParameters()->size())
2203 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2204
2205 Decl *Param
2206 = const_cast<NamedDecl *>(
2207 Partial->getTemplateParameters()->getParam(ParamIdx));
2208 Info.Param = makeTemplateParameter(Param);
2209 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2210 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002211 }
2212
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002213 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002214 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002215 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002216 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002217
Douglas Gregorca4686d2011-01-04 23:35:54 +00002218 TemplateParameterList *TemplateParams
2219 = ClassTemplate->getTemplateParameters();
2220 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002221 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002222 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002223 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002224 Info.FirstArg = TemplateArgs[I];
2225 Info.SecondArg = InstArg;
2226 return Sema::TDK_NonDeducedMismatch;
2227 }
2228 }
2229
2230 if (Trap.hasErrorOccurred())
2231 return Sema::TDK_SubstitutionFailure;
2232
2233 return Sema::TDK_Success;
2234}
2235
Douglas Gregor170bc422009-06-12 22:31:52 +00002236/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002237/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002238/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002239Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002240Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002241 const TemplateArgumentList &TemplateArgs,
2242 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002243 if (Partial->isInvalidDecl())
2244 return TDK_Invalid;
2245
Douglas Gregor170bc422009-06-12 22:31:52 +00002246 // C++ [temp.class.spec.match]p2:
2247 // A partial specialization matches a given actual template
2248 // argument list if the template arguments of the partial
2249 // specialization can be deduced from the actual template argument
2250 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002251
2252 // Unevaluated SFINAE context.
2253 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002254 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002255
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002256 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002257 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002258 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002259 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002260 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002261 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002262 TemplateArgs, Info, Deduced))
2263 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002264
Richard Smith80934652012-07-16 01:09:10 +00002265 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002266 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2267 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002268 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002269 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002270
Douglas Gregore1416332009-06-14 08:02:22 +00002271 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002272 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002273
2274 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002275 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002276}
Douglas Gregor91772d12009-06-13 00:26:55 +00002277
Larisse Voufo39a1e502013-08-06 01:03:05 +00002278/// Complete template argument deduction for a variable template partial
2279/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002280/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2281/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2282/// VarTemplate(Partial)SpecializationDecl with a new data
2283/// structure Template(Partial)SpecializationDecl, and
2284/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002285static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2286 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2287 const TemplateArgumentList &TemplateArgs,
2288 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2289 TemplateDeductionInfo &Info) {
2290 // Unevaluated SFINAE context.
2291 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2292 Sema::SFINAETrap Trap(S);
2293
2294 // C++ [temp.deduct.type]p2:
2295 // [...] or if any template argument remains neither deduced nor
2296 // explicitly specified, template argument deduction fails.
2297 SmallVector<TemplateArgument, 4> Builder;
2298 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2299 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2300 NamedDecl *Param = PartialParams->getParam(I);
2301 if (Deduced[I].isNull()) {
2302 Info.Param = makeTemplateParameter(Param);
2303 return Sema::TDK_Incomplete;
2304 }
2305
2306 // We have deduced this argument, so it still needs to be
2307 // checked and converted.
2308
2309 // First, for a non-type template parameter type that is
2310 // initialized by a declaration, we need the type of the
2311 // corresponding non-type template parameter.
2312 QualType NTTPType;
2313 if (NonTypeTemplateParmDecl *NTTP =
2314 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2315 NTTPType = NTTP->getType();
2316 if (NTTPType->isDependentType()) {
2317 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2318 Builder.data(), Builder.size());
2319 NTTPType =
2320 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2321 NTTP->getLocation(), NTTP->getDeclName());
2322 if (NTTPType.isNull()) {
2323 Info.Param = makeTemplateParameter(Param);
2324 // FIXME: These template arguments are temporary. Free them!
2325 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2326 Builder.size()));
2327 return Sema::TDK_SubstitutionFailure;
2328 }
2329 }
2330 }
2331
2332 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2333 0, Info, false, Builder)) {
2334 Info.Param = makeTemplateParameter(Param);
2335 // FIXME: These template arguments are temporary. Free them!
2336 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2337 Builder.size()));
2338 return Sema::TDK_SubstitutionFailure;
2339 }
2340 }
2341
2342 // Form the template argument list from the deduced template arguments.
2343 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2344 S.Context, Builder.data(), Builder.size());
2345
2346 Info.reset(DeducedArgumentList);
2347
2348 // Substitute the deduced template arguments into the template
2349 // arguments of the class template partial specialization, and
2350 // verify that the instantiated template arguments are both valid
2351 // and are equivalent to the template arguments originally provided
2352 // to the class template.
2353 LocalInstantiationScope InstScope(S);
2354 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002355 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2356 = Partial->getTemplateArgsAsWritten();
2357 const TemplateArgumentLoc *PartialTemplateArgs
2358 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002359
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002360 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2361 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002362
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002363 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002364 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2365 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2366 if (ParamIdx >= Partial->getTemplateParameters()->size())
2367 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2368
2369 Decl *Param = const_cast<NamedDecl *>(
2370 Partial->getTemplateParameters()->getParam(ParamIdx));
2371 Info.Param = makeTemplateParameter(Param);
2372 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2373 return Sema::TDK_SubstitutionFailure;
2374 }
2375 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2376 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2377 false, ConvertedInstArgs))
2378 return Sema::TDK_SubstitutionFailure;
2379
2380 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2381 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2382 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2383 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2384 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2385 Info.FirstArg = TemplateArgs[I];
2386 Info.SecondArg = InstArg;
2387 return Sema::TDK_NonDeducedMismatch;
2388 }
2389 }
2390
2391 if (Trap.hasErrorOccurred())
2392 return Sema::TDK_SubstitutionFailure;
2393
2394 return Sema::TDK_Success;
2395}
2396
2397/// \brief Perform template argument deduction to determine whether
2398/// the given template arguments match the given variable template
2399/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002400/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2401/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2402/// VarTemplate(Partial)SpecializationDecl with a new data
2403/// structure Template(Partial)SpecializationDecl, and
2404/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002405Sema::TemplateDeductionResult
2406Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2407 const TemplateArgumentList &TemplateArgs,
2408 TemplateDeductionInfo &Info) {
2409 if (Partial->isInvalidDecl())
2410 return TDK_Invalid;
2411
2412 // C++ [temp.class.spec.match]p2:
2413 // A partial specialization matches a given actual template
2414 // argument list if the template arguments of the partial
2415 // specialization can be deduced from the actual template argument
2416 // list (14.8.2).
2417
2418 // Unevaluated SFINAE context.
2419 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2420 SFINAETrap Trap(*this);
2421
2422 SmallVector<DeducedTemplateArgument, 4> Deduced;
2423 Deduced.resize(Partial->getTemplateParameters()->size());
2424 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2425 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2426 TemplateArgs, Info, Deduced))
2427 return Result;
2428
2429 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002430 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2431 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002432 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002433 return TDK_InstantiationDepth;
2434
2435 if (Trap.hasErrorOccurred())
2436 return Sema::TDK_SubstitutionFailure;
2437
2438 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2439 Deduced, Info);
2440}
2441
Douglas Gregorfc516c92009-06-26 23:27:24 +00002442/// \brief Determine whether the given type T is a simple-template-id type.
2443static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002444 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002445 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002446 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002447
Douglas Gregorfc516c92009-06-26 23:27:24 +00002448 return false;
2449}
Douglas Gregor9b146582009-07-08 20:55:45 +00002450
2451/// \brief Substitute the explicitly-provided template arguments into the
2452/// given function template according to C++ [temp.arg.explicit].
2453///
2454/// \param FunctionTemplate the function template into which the explicit
2455/// template arguments will be substituted.
2456///
James Dennett634962f2012-06-14 21:40:34 +00002457/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002458/// arguments.
2459///
Mike Stump11289f42009-09-09 15:08:12 +00002460/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002461/// with the converted and checked explicit template arguments.
2462///
Mike Stump11289f42009-09-09 15:08:12 +00002463/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002464/// parameters.
2465///
2466/// \param FunctionType if non-NULL, the result type of the function template
2467/// will also be instantiated and the pointed-to value will be updated with
2468/// the instantiated function type.
2469///
2470/// \param Info if substitution fails for any reason, this object will be
2471/// populated with more information about the failure.
2472///
2473/// \returns TDK_Success if substitution was successful, or some failure
2474/// condition.
2475Sema::TemplateDeductionResult
2476Sema::SubstituteExplicitTemplateArguments(
2477 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002478 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002479 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2480 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002481 QualType *FunctionType,
2482 TemplateDeductionInfo &Info) {
2483 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2484 TemplateParameterList *TemplateParams
2485 = FunctionTemplate->getTemplateParameters();
2486
John McCall6b51f282009-11-23 01:53:49 +00002487 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002488 // No arguments to substitute; just copy over the parameter types and
2489 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002490 for (auto P : Function->params())
2491 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregor9b146582009-07-08 20:55:45 +00002493 if (FunctionType)
2494 *FunctionType = Function->getType();
2495 return TDK_Success;
2496 }
Mike Stump11289f42009-09-09 15:08:12 +00002497
Eli Friedman77dcc722012-02-08 03:07:05 +00002498 // Unevaluated SFINAE context.
2499 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002500 SFINAETrap Trap(*this);
2501
Douglas Gregor9b146582009-07-08 20:55:45 +00002502 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002503 // Template arguments that are present shall be specified in the
2504 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002505 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002506 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002507 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002508
2509 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002510 // explicitly-specified template arguments against this function template,
2511 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002512 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002513 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2514 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002515 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2516 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002517 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002518 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002519
Douglas Gregor9b146582009-07-08 20:55:45 +00002520 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002521 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002522 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002523 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002524 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002525 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002526 if (Index >= TemplateParams->size())
2527 Index = TemplateParams->size() - 1;
2528 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002529 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor9b146582009-07-08 20:55:45 +00002532 // Form the template argument list from the explicitly-specified
2533 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002534 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002535 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002536 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002537
John McCall036855a2010-10-12 19:40:14 +00002538 // Template argument deduction and the final substitution should be
2539 // done in the context of the templated declaration. Explicit
2540 // argument substitution, on the other hand, needs to happen in the
2541 // calling context.
2542 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2543
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002545 // note that the template argument pack is partially substituted and record
2546 // the explicit template arguments. They'll be used as part of deduction
2547 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002548 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2549 const TemplateArgument &Arg = Builder[I];
2550 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002551 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002553 Arg.pack_begin(),
2554 Arg.pack_size());
2555 break;
2556 }
2557 }
2558
Richard Smith5e580292012-02-10 09:58:53 +00002559 const FunctionProtoType *Proto
2560 = Function->getType()->getAs<FunctionProtoType>();
2561 assert(Proto && "Function template does not have a prototype?");
2562
Richard Smith70b13042015-01-09 01:19:56 +00002563 // Isolate our substituted parameters from our caller.
2564 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2565
Douglas Gregor9b146582009-07-08 20:55:45 +00002566 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002567 // explicitly-specified template arguments. If the function has a trailing
2568 // return type, substitute it after the arguments to ensure we substitute
2569 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002570 if (Proto->hasTrailingReturn()) {
2571 if (SubstParmTypes(Function->getLocation(),
2572 Function->param_begin(), Function->getNumParams(),
2573 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2574 ParamTypes))
2575 return TDK_SubstitutionFailure;
2576 }
2577
Richard Smith5e580292012-02-10 09:58:53 +00002578 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002579 QualType ResultType;
2580 {
2581 // C++11 [expr.prim.general]p3:
2582 // If a declaration declares a member function or member function
2583 // template of a class X, the expression this is a prvalue of type
2584 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2585 // and the end of the function-definition, member-declarator, or
2586 // declarator.
2587 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002588 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2590 ThisContext = Method->getParent();
2591 ThisTypeQuals = Method->getTypeQualifiers();
2592 }
2593
2594 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002595 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002596
2597 ResultType =
2598 SubstType(Proto->getReturnType(),
2599 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2600 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002601 if (ResultType.isNull() || Trap.hasErrorOccurred())
2602 return TDK_SubstitutionFailure;
2603 }
2604
Richard Smith5e580292012-02-10 09:58:53 +00002605 // Instantiate the types of each of the function parameters given the
2606 // explicitly-specified template arguments if we didn't do so earlier.
2607 if (!Proto->hasTrailingReturn() &&
2608 SubstParmTypes(Function->getLocation(),
2609 Function->param_begin(), Function->getNumParams(),
2610 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2611 ParamTypes))
2612 return TDK_SubstitutionFailure;
2613
Douglas Gregor9b146582009-07-08 20:55:45 +00002614 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002615 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002616 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002617 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002618 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002619 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2620 return TDK_SubstitutionFailure;
2621 }
Mike Stump11289f42009-09-09 15:08:12 +00002622
Douglas Gregor9b146582009-07-08 20:55:45 +00002623 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002624 // Trailing template arguments that can be deduced (14.8.2) may be
2625 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002626 // template arguments can be deduced, they may all be omitted; in this
2627 // case, the empty template argument list <> itself may also be omitted.
2628 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002629 // Take all of the explicitly-specified arguments and put them into
2630 // the set of deduced template arguments. Explicitly-specified
2631 // parameter packs, however, will be set to NULL since the deduction
2632 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002633 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002634 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2635 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2636 if (Arg.getKind() == TemplateArgument::Pack)
2637 Deduced.push_back(DeducedTemplateArgument());
2638 else
2639 Deduced.push_back(Arg);
2640 }
Mike Stump11289f42009-09-09 15:08:12 +00002641
Douglas Gregor9b146582009-07-08 20:55:45 +00002642 return TDK_Success;
2643}
2644
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002645/// \brief Check whether the deduced argument type for a call to a function
2646/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2647static bool
2648CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2649 QualType DeducedA) {
2650 ASTContext &Context = S.Context;
2651
2652 QualType A = OriginalArg.OriginalArgType;
2653 QualType OriginalParamType = OriginalArg.OriginalParamType;
2654
2655 // Check for type equality (top-level cv-qualifiers are ignored).
2656 if (Context.hasSameUnqualifiedType(A, DeducedA))
2657 return false;
2658
2659 // Strip off references on the argument types; they aren't needed for
2660 // the following checks.
2661 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2662 DeducedA = DeducedARef->getPointeeType();
2663 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2664 A = ARef->getPointeeType();
2665
2666 // C++ [temp.deduct.call]p4:
2667 // [...] However, there are three cases that allow a difference:
2668 // - If the original P is a reference type, the deduced A (i.e., the
2669 // type referred to by the reference) can be more cv-qualified than
2670 // the transformed A.
2671 if (const ReferenceType *OriginalParamRef
2672 = OriginalParamType->getAs<ReferenceType>()) {
2673 // We don't want to keep the reference around any more.
2674 OriginalParamType = OriginalParamRef->getPointeeType();
2675
2676 Qualifiers AQuals = A.getQualifiers();
2677 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002678
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002679 // Under Objective-C++ ARC, the deduced type may have implicitly
2680 // been given strong or (when dealing with a const reference)
2681 // unsafe_unretained lifetime. If so, update the original
2682 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002683 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002684 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2685 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2686 (DeducedAQuals.hasConst() &&
2687 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2688 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002689 }
2690
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002691 if (AQuals == DeducedAQuals) {
2692 // Qualifiers match; there's nothing to do.
2693 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002694 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002695 } else {
2696 // Qualifiers are compatible, so have the argument type adopt the
2697 // deduced argument type's qualifiers as if we had performed the
2698 // qualification conversion.
2699 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2700 }
2701 }
2702
2703 // - The transformed A can be another pointer or pointer to member
2704 // type that can be converted to the deduced A via a qualification
2705 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002706 //
2707 // Also allow conversions which merely strip [[noreturn]] from function types
2708 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002709 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002710 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002711 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002712 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002713 (S.IsQualificationConversion(A, DeducedA, false,
2714 ObjCLifetimeConversion) ||
2715 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002716 return false;
2717
2718
2719 // - If P is a class and P has the form simple-template-id, then the
2720 // transformed A can be a derived class of the deduced A. [...]
2721 // [...] Likewise, if P is a pointer to a class of the form
2722 // simple-template-id, the transformed A can be a pointer to a
2723 // derived class pointed to by the deduced A.
2724 if (const PointerType *OriginalParamPtr
2725 = OriginalParamType->getAs<PointerType>()) {
2726 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2727 if (const PointerType *APtr = A->getAs<PointerType>()) {
2728 if (A->getPointeeType()->isRecordType()) {
2729 OriginalParamType = OriginalParamPtr->getPointeeType();
2730 DeducedA = DeducedAPtr->getPointeeType();
2731 A = APtr->getPointeeType();
2732 }
2733 }
2734 }
2735 }
2736
2737 if (Context.hasSameUnqualifiedType(A, DeducedA))
2738 return false;
2739
2740 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002741 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002742 return false;
2743
2744 return true;
2745}
2746
Mike Stump11289f42009-09-09 15:08:12 +00002747/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002748/// checking the deduced template arguments for completeness and forming
2749/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002750///
2751/// \param OriginalCallArgs If non-NULL, the original call arguments against
2752/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002753Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002754Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002755 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002756 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002757 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002758 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002759 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2760 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002761 TemplateParameterList *TemplateParams
2762 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002763
Eli Friedman77dcc722012-02-08 03:07:05 +00002764 // Unevaluated SFINAE context.
2765 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002766 SFINAETrap Trap(*this);
2767
Douglas Gregor9b146582009-07-08 20:55:45 +00002768 // Enter a new template instantiation context while we instantiate the
2769 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002770 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002771 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2772 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002773 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2774 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002775 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002776 return TDK_InstantiationDepth;
2777
John McCalle23b8712010-04-29 01:18:58 +00002778 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002779
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002780 // C++ [temp.deduct.type]p2:
2781 // [...] or if any template argument remains neither deduced nor
2782 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002783 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002784 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2785 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002787 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002788 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002789 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002791 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002792 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002793 // We may have had explicitly-specified template arguments for a
2794 // template parameter pack (that may or may not have been extended
2795 // via additional deduced arguments).
2796 if (Param->isParameterPack() && CurrentInstantiationScope) {
2797 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2798 Param) {
2799 // Forget the partially-substituted pack; its substitution is now
2800 // complete.
2801 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2802 }
2803 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002804 continue;
2805 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002806 // We have deduced this argument, so it still needs to be
2807 // checked and converted.
2808
2809 // First, for a non-type template parameter type that is
2810 // initialized by a declaration, we need the type of the
2811 // corresponding non-type template parameter.
2812 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813 if (NonTypeTemplateParmDecl *NTTP
2814 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002815 NTTPType = NTTP->getType();
2816 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002818 Builder.data(), Builder.size());
2819 NTTPType = SubstType(NTTPType,
2820 MultiLevelTemplateArgumentList(TemplateArgs),
2821 NTTP->getLocation(),
2822 NTTP->getDeclName());
2823 if (NTTPType.isNull()) {
2824 Info.Param = makeTemplateParameter(Param);
2825 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 Info.reset(TemplateArgumentList::CreateCopy(Context,
2827 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002828 Builder.size()));
2829 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002830 }
2831 }
2832 }
2833
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002834 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002835 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002836 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002837 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002838 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002839 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2840 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002841 return TDK_SubstitutionFailure;
2842 }
2843
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002844 continue;
2845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002847 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002849 // be deduced to an empty sequence of template arguments.
2850 // FIXME: Where did the word "trailing" come from?
2851 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002852 // We may have had explicitly-specified template arguments for this
2853 // template parameter pack. If so, our empty deduction extends the
2854 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2855 const TemplateArgument *ExplicitArgs;
2856 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002857 if (CurrentInstantiationScope &&
2858 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002859 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002860 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002861 Builder.push_back(TemplateArgument(
2862 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
Douglas Gregorcaddba92013-01-18 22:27:09 +00002864 // Forget the partially-substituted pack; it's substitution is now
2865 // complete.
2866 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2867 } else {
2868 Builder.push_back(TemplateArgument::getEmptyPack());
2869 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002870 continue;
2871 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002872
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002874 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002875 TemplateArgumentLoc DefArg
2876 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2877 FunctionTemplate->getLocation(),
2878 FunctionTemplate->getSourceRange().getEnd(),
2879 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002880 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002881
2882 // If there was no default argument, deduction is incomplete.
2883 if (DefArg.getArgument().isNull()) {
2884 Info.Param = makeTemplateParameter(
2885 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002886 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2887 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002888 if (PartialOverloading) break;
2889
Richard Smithc87b9382013-07-04 01:01:24 +00002890 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002891 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002893 // Check whether we can actually use the default argument.
2894 if (CheckTemplateArgument(Param, DefArg,
2895 FunctionTemplate,
2896 FunctionTemplate->getLocation(),
2897 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002898 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002899 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002900 Info.Param = makeTemplateParameter(
2901 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002902 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002904 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002905 return TDK_SubstitutionFailure;
2906 }
2907
2908 // If we get here, we successfully used the default template argument.
2909 }
2910
2911 // Form the template argument list from the deduced template arguments.
2912 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002913 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002914 Info.reset(DeducedArgumentList);
2915
Mike Stump11289f42009-09-09 15:08:12 +00002916 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002917 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002918 DeclContext *Owner = FunctionTemplate->getDeclContext();
2919 if (FunctionTemplate->getFriendObjectKind())
2920 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002921 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002922 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002923 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002924 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002925 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002926
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002928 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Mike Stump11289f42009-09-09 15:08:12 +00002930 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002931 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002932 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2933 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002934 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002935
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002936 // There may have been an error that did not prevent us from constructing a
2937 // declaration. Mark the declaration invalid and return with a substitution
2938 // failure.
2939 if (Trap.hasErrorOccurred()) {
2940 Specialization->setInvalidDecl(true);
2941 return TDK_SubstitutionFailure;
2942 }
2943
Douglas Gregore65aacb2011-06-16 16:50:48 +00002944 if (OriginalCallArgs) {
2945 // C++ [temp.deduct.call]p4:
2946 // In general, the deduction process attempts to find template argument
2947 // values that will make the deduced A identical to A (after the type A
2948 // is transformed as described above). [...]
2949 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2950 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002951 unsigned ParamIdx = OriginalArg.ArgIdx;
2952
2953 if (ParamIdx >= Specialization->getNumParams())
2954 continue;
2955
2956 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002957 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2958 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002959 }
2960 }
2961
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002962 // If we suppressed any diagnostics while performing template argument
2963 // deduction, and if we haven't already instantiated this declaration,
2964 // keep track of these diagnostics. They'll be emitted if this specialization
2965 // is actually used.
2966 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002967 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002968 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2969 if (Pos == SuppressedDiagnostics.end())
2970 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2971 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002973
Mike Stump11289f42009-09-09 15:08:12 +00002974 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002975}
2976
John McCall8d08b9b2010-08-27 09:08:28 +00002977/// Gets the type of a function for template-argument-deducton
2978/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002979static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002980 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002981 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002982 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002983 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002984 return QualType();
2985
John McCallc1f69982010-02-02 02:21:27 +00002986 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002987 if (Method->isInstance()) {
2988 // An instance method that's referenced in a form that doesn't
2989 // look like a member pointer is just invalid.
2990 if (!R.HasFormOfMemberPointer) return QualType();
2991
Richard Smith2a7d4812013-05-04 07:00:32 +00002992 return S.Context.getMemberPointerType(Fn->getType(),
2993 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002994 }
2995
2996 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002997 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002998}
2999
3000/// Apply the deduction rules for overload sets.
3001///
3002/// \return the null type if this argument should be treated as an
3003/// undeduced context
3004static QualType
3005ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003006 Expr *Arg, QualType ParamType,
3007 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003008
John McCall8d08b9b2010-08-27 09:08:28 +00003009 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003010
John McCall8d08b9b2010-08-27 09:08:28 +00003011 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003012
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003013 // C++0x [temp.deduct.call]p4
3014 unsigned TDF = 0;
3015 if (ParamWasReference)
3016 TDF |= TDF_ParamWithReferenceType;
3017 if (R.IsAddressOfOperand)
3018 TDF |= TDF_IgnoreQualifiers;
3019
John McCallc1f69982010-02-02 02:21:27 +00003020 // C++0x [temp.deduct.call]p6:
3021 // When P is a function type, pointer to function type, or pointer
3022 // to member function type:
3023
3024 if (!ParamType->isFunctionType() &&
3025 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003026 !ParamType->isMemberFunctionPointerType()) {
3027 if (Ovl->hasExplicitTemplateArgs()) {
3028 // But we can still look for an explicit specialization.
3029 if (FunctionDecl *ExplicitSpec
3030 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003031 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003032 }
John McCallc1f69982010-02-02 02:21:27 +00003033
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003034 return QualType();
3035 }
3036
3037 // Gather the explicit template arguments, if any.
3038 TemplateArgumentListInfo ExplicitTemplateArgs;
3039 if (Ovl->hasExplicitTemplateArgs())
3040 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003041 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003042 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3043 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003044 NamedDecl *D = (*I)->getUnderlyingDecl();
3045
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003046 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3047 // - If the argument is an overload set containing one or more
3048 // function templates, the parameter is treated as a
3049 // non-deduced context.
3050 if (!Ovl->hasExplicitTemplateArgs())
3051 return QualType();
3052
3053 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003054 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003055 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003056 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3057 Specialization, Info))
3058 continue;
3059
3060 D = Specialization;
3061 }
John McCallc1f69982010-02-02 02:21:27 +00003062
3063 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003064 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003065 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003066
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003067 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003068 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003069 ArgType->isFunctionType())
3070 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003071
John McCallc1f69982010-02-02 02:21:27 +00003072 // - If the argument is an overload set (not containing function
3073 // templates), trial argument deduction is attempted using each
3074 // of the members of the set. If deduction succeeds for only one
3075 // of the overload set members, that member is used as the
3076 // argument value for the deduction. If deduction succeeds for
3077 // more than one member of the overload set the parameter is
3078 // treated as a non-deduced context.
3079
3080 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3081 // Type deduction is done independently for each P/A pair, and
3082 // the deduced template argument values are then combined.
3083 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003084 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003085 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003086 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003087 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003088 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3089 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003090 if (Result) continue;
3091 if (!Match.isNull()) return QualType();
3092 Match = ArgType;
3093 }
3094
3095 return Match;
3096}
3097
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003099/// described in C++ [temp.deduct.call].
3100///
3101/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003102/// argument deduction based on this P/A pair because the argument is an
3103/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003104static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3105 TemplateParameterList *TemplateParams,
3106 QualType &ParamType,
3107 QualType &ArgType,
3108 Expr *Arg,
3109 unsigned &TDF) {
3110 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003111 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003112 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003113 if (ParamType.hasQualifiers())
3114 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003115
3116 // [...] If P is a reference type, the type referred to by P is
3117 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003118 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003119 if (ParamRefType)
3120 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003121
Nathan Sidwell96090022015-01-16 15:20:14 +00003122 // Overload sets usually make this parameter an undeduced context,
3123 // but there are sometimes special circumstances. Typically
3124 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125 if (ArgType == S.Context.OverloadTy) {
3126 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3127 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003128 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003129 if (ArgType.isNull())
3130 return true;
3131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132
Douglas Gregor7825bf32011-01-06 22:09:01 +00003133 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003134 // If the argument has incomplete array type, try to complete its type.
3135 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
3136 ArgType = Arg->getType();
3137
Douglas Gregor7825bf32011-01-06 22:09:01 +00003138 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003139 // If P is an rvalue reference to a cv-unqualified template
3140 // parameter and the argument is an lvalue, the type "lvalue
3141 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003142 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003143 !ParamType.getQualifiers() &&
3144 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003145 Arg->isLValue())
3146 ArgType = S.Context.getLValueReferenceType(ArgType);
3147 } else {
3148 // C++ [temp.deduct.call]p2:
3149 // If P is not a reference type:
3150 // - If A is an array type, the pointer type produced by the
3151 // array-to-pointer standard conversion (4.2) is used in place of
3152 // A for type deduction; otherwise,
3153 if (ArgType->isArrayType())
3154 ArgType = S.Context.getArrayDecayedType(ArgType);
3155 // - If A is a function type, the pointer type produced by the
3156 // function-to-pointer standard conversion (4.3) is used in place
3157 // of A for type deduction; otherwise,
3158 else if (ArgType->isFunctionType())
3159 ArgType = S.Context.getPointerType(ArgType);
3160 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003161 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003162 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003163 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003164 }
3165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor7825bf32011-01-06 22:09:01 +00003167 // C++0x [temp.deduct.call]p4:
3168 // In general, the deduction process attempts to find template argument
3169 // values that will make the deduced A identical to A (after the type A
3170 // is transformed as described above). [...]
3171 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003172
Douglas Gregor7825bf32011-01-06 22:09:01 +00003173 // - If the original P is a reference type, the deduced A (i.e., the
3174 // type referred to by the reference) can be more cv-qualified than
3175 // the transformed A.
3176 if (ParamRefType)
3177 TDF |= TDF_ParamWithReferenceType;
3178 // - The transformed A can be another pointer or pointer to member
3179 // type that can be converted to the deduced A via a qualification
3180 // conversion (4.4).
3181 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3182 ArgType->isObjCObjectPointerType())
3183 TDF |= TDF_IgnoreQualifiers;
3184 // - If P is a class and P has the form simple-template-id, then the
3185 // transformed A can be a derived class of the deduced A. Likewise,
3186 // if P is a pointer to a class of the form simple-template-id, the
3187 // transformed A can be a pointer to a derived class pointed to by
3188 // the deduced A.
3189 if (isSimpleTemplateIdType(ParamType) ||
3190 (isa<PointerType>(ParamType) &&
3191 isSimpleTemplateIdType(
3192 ParamType->getAs<PointerType>()->getPointeeType())))
3193 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194
Douglas Gregor7825bf32011-01-06 22:09:01 +00003195 return false;
3196}
3197
Nico Weberc153d242014-07-28 00:02:09 +00003198static bool
3199hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3200 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003201
Hubert Tong3280b332015-06-25 00:25:49 +00003202static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3203 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3204 Expr *Arg, TemplateDeductionInfo &Info,
3205 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3206
3207/// \brief Attempt template argument deduction from an initializer list
3208/// deemed to be an argument in a function call.
3209static bool
3210DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3211 QualType AdjustedParamType, InitListExpr *ILE,
3212 TemplateDeductionInfo &Info,
3213 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3214 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003215
3216 // [temp.deduct.call] p1 (post CWG-1591)
3217 // If removing references and cv-qualifiers from P gives
3218 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3219 // non-empty initializer list (8.5.4), then deduction is performed instead for
3220 // each element of the initializer list, taking P0 as a function template
3221 // parameter type and the initializer element as its argument, and in the
3222 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3223 // length of the initializer list. Otherwise, an initializer list argument
3224 // causes the parameter to be considered a non-deduced context
3225
3226 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3227
3228 const bool IsDependentSizedArray =
3229 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3230
Faisal Validd76cc12015-12-10 12:29:11 +00003231 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003232
3233 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3234 S.isStdInitializerList(AdjustedParamType, &ElTy);
3235
3236 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003237 return false;
3238
3239 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003240 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3241 // deduce against the 'T' in T[N].
3242 if (ElTy.isNull()) {
3243 assert(!IsSTDList);
3244 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003245 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003246 // Deduction only needs to be done for dependent types.
3247 if (ElTy->isDependentType()) {
3248 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003249 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3250 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003251 return true;
3252 }
3253 }
3254 if (IsDependentSizedArray) {
3255 const DependentSizedArrayType *ArrTy =
3256 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3257 // Determine the array bound is something we can deduce.
3258 if (NonTypeTemplateParmDecl *NTTP =
3259 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3260 // We can perform template argument deduction for the given non-type
3261 // template parameter.
3262 assert(NTTP->getDepth() == 0 &&
3263 "Cannot deduce non-type template argument at depth > 0");
3264 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3265 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003266
Faisal Valif6dfdb32015-12-10 05:36:39 +00003267 Result = DeduceNonTypeTemplateArgument(
3268 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3269 /*ArrayBound=*/true, Info, Deduced);
3270 }
3271 }
Hubert Tong3280b332015-06-25 00:25:49 +00003272 return true;
3273}
3274
Sebastian Redl19181662012-03-15 21:40:51 +00003275/// \brief Perform template argument deduction by matching a parameter type
3276/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003277/// an initializer list that was originally matched against a parameter
3278/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003279static Sema::TemplateDeductionResult
3280DeduceTemplateArgumentByListElement(Sema &S,
3281 TemplateParameterList *TemplateParams,
3282 QualType ParamType, Expr *Arg,
3283 TemplateDeductionInfo &Info,
3284 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3285 unsigned TDF) {
3286 // Handle the case where an init list contains another init list as the
3287 // element.
3288 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003289 Sema::TemplateDeductionResult Result;
3290 if (!DeduceFromInitializerList(S, TemplateParams,
3291 ParamType.getNonReferenceType(), ILE, Info,
3292 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003293 return Sema::TDK_Success; // Just ignore this expression.
3294
Hubert Tong3280b332015-06-25 00:25:49 +00003295 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003296 }
3297
3298 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003299 QualType ArgType = Arg->getType();
3300 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003301 ArgType, Arg, TDF)) {
3302 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003303 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003304 }
Sebastian Redl19181662012-03-15 21:40:51 +00003305 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003306 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003307}
3308
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003309/// \brief Perform template argument deduction from a function call
3310/// (C++ [temp.deduct.call]).
3311///
3312/// \param FunctionTemplate the function template for which we are performing
3313/// template argument deduction.
3314///
James Dennett18348b62012-06-22 08:52:37 +00003315/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003316/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003317///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003318/// \param Args the function call arguments
3319///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003320/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003321/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322/// template argument deduction.
3323///
3324/// \param Info the argument will be updated to provide additional information
3325/// about template argument deduction.
3326///
3327/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003328Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3329 FunctionTemplateDecl *FunctionTemplate,
3330 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003331 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3332 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003333 if (FunctionTemplate->isInvalidDecl())
3334 return TDK_Invalid;
3335
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003336 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003337 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003338
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003339 // C++ [temp.deduct.call]p1:
3340 // Template argument deduction is done by comparing each function template
3341 // parameter type (call it P) with the type of the corresponding argument
3342 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003343 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003344 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003345 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003346 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003347 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003348 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003349 if (Proto->isTemplateVariadic())
3350 /* Do nothing */;
3351 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003352 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003355 }
Mike Stump11289f42009-09-09 15:08:12 +00003356
Douglas Gregor89026b52009-06-30 23:57:56 +00003357 // The types of the parameters from which we will perform template argument
3358 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003359 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003360 TemplateParameterList *TemplateParams
3361 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003362 SmallVector<DeducedTemplateArgument, 4> Deduced;
3363 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003364 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003365 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003366 TemplateDeductionResult Result =
3367 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003368 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003369 Deduced,
3370 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003371 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003372 Info);
3373 if (Result)
3374 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003375
3376 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003377 } else {
3378 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003379 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003380 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3381 }
Mike Stump11289f42009-09-09 15:08:12 +00003382
Douglas Gregor89026b52009-06-30 23:57:56 +00003383 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003384 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003385 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003386 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003387 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3388 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003389 QualType OrigParamType = ParamTypes[ParamIdx];
3390 QualType ParamType = OrigParamType;
3391
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003393 = dyn_cast<PackExpansionType>(ParamType);
3394 if (!ParamExpansion) {
3395 // Simple case: matching a function parameter to a function argument.
3396 if (ArgIdx >= CheckArgs)
3397 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Douglas Gregor7825bf32011-01-06 22:09:01 +00003399 Expr *Arg = Args[ArgIdx++];
3400 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003401
Douglas Gregor7825bf32011-01-06 22:09:01 +00003402 unsigned TDF = 0;
3403 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3404 ParamType, ArgType, Arg,
3405 TDF))
3406 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407
Douglas Gregor0c83c812011-10-09 22:06:46 +00003408 // If we have nothing to deduce, we're done.
3409 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3410 continue;
3411
Sebastian Redl43144e72012-01-17 22:49:58 +00003412 // If the argument is an initializer list ...
3413 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003414 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003415 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003416 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3417 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003418 continue;
3419
Hubert Tong3280b332015-06-25 00:25:49 +00003420 if (Result)
3421 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003422 // Don't track the argument type, since an initializer list has none.
3423 continue;
3424 }
3425
Douglas Gregore65aacb2011-06-16 16:50:48 +00003426 // Keep track of the argument type and corresponding parameter index,
3427 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003428 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3429 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003430
Douglas Gregor7825bf32011-01-06 22:09:01 +00003431 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003432 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3433 ParamType, ArgType,
3434 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003435 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003436
Douglas Gregor7825bf32011-01-06 22:09:01 +00003437 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregor7825bf32011-01-06 22:09:01 +00003440 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 // For a function parameter pack that occurs at the end of the
3442 // parameter-declaration-list, the type A of each remaining argument of
3443 // the call is compared with the type P of the declarator-id of the
3444 // function parameter pack. Each comparison deduces template arguments
3445 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003446 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003448 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003449 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003450 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregor7825bf32011-01-06 22:09:01 +00003452 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003453 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3454 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregor7825bf32011-01-06 22:09:01 +00003456 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003457 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003458 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregore65aacb2011-06-16 16:50:48 +00003460 QualType OrigParamType = ParamPattern;
3461 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003462 Expr *Arg = Args[ArgIdx];
3463 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003464
Douglas Gregor7825bf32011-01-06 22:09:01 +00003465 unsigned TDF = 0;
3466 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3467 ParamType, ArgType, Arg,
3468 TDF)) {
3469 // We can't actually perform any deduction for this argument, so stop
3470 // deduction at this point.
3471 ++ArgIdx;
3472 break;
3473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474
Sebastian Redl43144e72012-01-17 22:49:58 +00003475 // As above, initializer lists need special handling.
3476 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003477 TemplateDeductionResult Result;
3478 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3479 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003480 ++ArgIdx;
3481 break;
3482 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003483
Hubert Tong3280b332015-06-25 00:25:49 +00003484 if (Result)
3485 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003486 } else {
3487
3488 // Keep track of the argument type and corresponding argument index,
3489 // so we can check for compatibility between the deduced A and A.
3490 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3491 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3492 ArgType));
3493
3494 if (TemplateDeductionResult Result
3495 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3496 ParamType, ArgType, Info,
3497 Deduced, TDF))
3498 return Result;
3499 }
Mike Stump11289f42009-09-09 15:08:12 +00003500
Richard Smith0a80d572014-05-29 01:12:14 +00003501 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregor7825bf32011-01-06 22:09:01 +00003504 // Build argument packs for each of the parameter packs expanded by this
3505 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003506 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregor7825bf32011-01-06 22:09:01 +00003509 // After we've matching against a parameter pack, we're done.
3510 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003511 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003512
Mike Stump11289f42009-09-09 15:08:12 +00003513 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003514 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003515 Info, &OriginalCallArgs,
3516 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003517}
3518
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003519QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3520 QualType FunctionType) {
3521 if (ArgFunctionType.isNull())
3522 return ArgFunctionType;
3523
3524 const FunctionProtoType *FunctionTypeP =
3525 FunctionType->castAs<FunctionProtoType>();
3526 CallingConv CC = FunctionTypeP->getCallConv();
3527 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3528 const FunctionProtoType *ArgFunctionTypeP =
3529 ArgFunctionType->getAs<FunctionProtoType>();
3530 if (ArgFunctionTypeP->getCallConv() == CC &&
3531 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3532 return ArgFunctionType;
3533
3534 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3535 EI = EI.withNoReturn(NoReturn);
3536 ArgFunctionTypeP =
3537 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3538 return QualType(ArgFunctionTypeP, 0);
3539}
3540
Douglas Gregor9b146582009-07-08 20:55:45 +00003541/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003542/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3543/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003544///
3545/// \param FunctionTemplate the function template for which we are performing
3546/// template argument deduction.
3547///
James Dennett18348b62012-06-22 08:52:37 +00003548/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003549/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003550///
3551/// \param ArgFunctionType the function type that will be used as the
3552/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003553/// function template's function type. This type may be NULL, if there is no
3554/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003555///
3556/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003557/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003558/// template argument deduction.
3559///
3560/// \param Info the argument will be updated to provide additional information
3561/// about template argument deduction.
3562///
3563/// \returns the result of template argument deduction.
3564Sema::TemplateDeductionResult
3565Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003566 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003567 QualType ArgFunctionType,
3568 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003569 TemplateDeductionInfo &Info,
3570 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003571 if (FunctionTemplate->isInvalidDecl())
3572 return TDK_Invalid;
3573
Douglas Gregor9b146582009-07-08 20:55:45 +00003574 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3575 TemplateParameterList *TemplateParams
3576 = FunctionTemplate->getTemplateParameters();
3577 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003578 if (!InOverloadResolution)
3579 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Douglas Gregor9b146582009-07-08 20:55:45 +00003581 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003582 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003583 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003584 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003585 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003586 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003587 if (TemplateDeductionResult Result
3588 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003589 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003590 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003591 &FunctionType, Info))
3592 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003593
3594 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003595 }
3596
Eli Friedman77dcc722012-02-08 03:07:05 +00003597 // Unevaluated SFINAE context.
3598 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003599 SFINAETrap Trap(*this);
3600
John McCallc1f69982010-02-02 02:21:27 +00003601 Deduced.resize(TemplateParams->size());
3602
Richard Smith2a7d4812013-05-04 07:00:32 +00003603 // If the function has a deduced return type, substitute it for a dependent
3604 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003605 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003606 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003607 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003608 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003609 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003610 }
3611
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003612 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003613 unsigned TDF = TDF_TopLevelParameterTypeList;
3614 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003615 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003616 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003617 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003618 FunctionType, ArgFunctionType,
3619 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003620 return Result;
3621 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003622
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003624 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3625 NumExplicitlySpecified,
3626 Specialization, Info))
3627 return Result;
3628
Richard Smith2a7d4812013-05-04 07:00:32 +00003629 // If the function has a deduced return type, deduce it now, so we can check
3630 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003631 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003632 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003633 DeduceReturnType(Specialization, Info.getLocation(), false))
3634 return TDK_MiscellaneousDeductionFailure;
3635
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003636 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003637 // specialization with respect to arguments of compatible pointer to function
3638 // types, template argument deduction fails.
3639 if (!ArgFunctionType.isNull()) {
3640 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3641 Context.getCanonicalType(Specialization->getType()),
3642 Context.getCanonicalType(ArgFunctionType)))
3643 return TDK_MiscellaneousDeductionFailure;
3644 else if(!InOverloadResolution &&
3645 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3646 return TDK_MiscellaneousDeductionFailure;
3647 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003648
3649 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003650}
3651
Faisal Vali850da1a2013-09-29 17:08:32 +00003652/// \brief Given a function declaration (e.g. a generic lambda conversion
3653/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3655/// to replace 'auto' with and not the actual result type you want
3656/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003657static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003658SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003659 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003660 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003661 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003662 assert(AutoResultType->getContainedAutoType());
3663 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003664 TypeToReplaceAutoWith);
3665 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3666}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003667
3668/// \brief Given a specialized conversion operator of a generic lambda
3669/// create the corresponding specializations of the call operator and
3670/// the static-invoker. If the return type of the call operator is auto,
3671/// deduce its return type and check if that matches the
3672/// return type of the destination function ptr.
3673
3674static inline Sema::TemplateDeductionResult
3675SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3676 CXXConversionDecl *ConversionSpecialized,
3677 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3678 QualType ReturnTypeOfDestFunctionPtr,
3679 TemplateDeductionInfo &TDInfo,
3680 Sema &S) {
3681
3682 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3683 assert(LambdaClass && LambdaClass->isGenericLambda());
3684
3685 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003686 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003687 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3688 CallOpResultType->getContainedAutoType();
3689
3690 FunctionTemplateDecl *CallOpTemplate =
3691 CallOpGeneric->getDescribedFunctionTemplate();
3692
Craig Topperc3ec1492014-05-26 06:22:03 +00003693 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003694 // Use the deduced arguments of the conversion function, to specialize our
3695 // generic lambda's call operator.
3696 if (Sema::TemplateDeductionResult Result
3697 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3698 DeducedArguments,
3699 0, CallOpSpecialized, TDInfo))
3700 return Result;
3701
3702 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003703 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3704 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003705 S.DeduceReturnType(CallOpSpecialized,
3706 CallOpSpecialized->getPointOfInstantiation(),
3707 /*Diagnose*/ true);
3708
3709 // Check to see if the return type of the destination ptr-to-function
3710 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003711 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003712 ReturnTypeOfDestFunctionPtr))
3713 return Sema::TDK_NonDeducedMismatch;
3714 // Since we have succeeded in matching the source and destination
3715 // ptr-to-functions (now including return type), and have successfully
3716 // specialized our corresponding call operator, we are ready to
3717 // specialize the static invoker with the deduced arguments of our
3718 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003719 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003720 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3721 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3722
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003723#ifndef NDEBUG
3724 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3725#endif
3726 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 InvokerSpecialized, TDInfo);
3728 assert(Result == Sema::TDK_Success &&
3729 "If the call operator succeeded so should the invoker!");
3730 // Set the result type to match the corresponding call operator
3731 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003732 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3733 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734 // Be sure to get the type to replace 'auto' with and not
3735 // the full result type of the call op specialization
3736 // to substitute into the 'auto' of the invoker and conversion
3737 // function.
3738 // For e.g.
3739 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3740 // We don't want to subst 'int*' into 'auto' to get int**.
3741
Alp Toker314cc812014-01-25 16:55:45 +00003742 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3743 ->getContainedAutoType()
3744 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003745 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3746 TypeToReplaceAutoWith, S);
3747 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3748 TypeToReplaceAutoWith, S);
3749 }
3750
3751 // Ensure that static invoker doesn't have a const qualifier.
3752 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3753 // do not use the CallOperator's TypeSourceInfo which allows
3754 // the const qualifier to leak through.
3755 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3756 getType().getTypePtr()->castAs<FunctionProtoType>();
3757 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3758 EPI.TypeQuals = 0;
3759 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003760 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003761 return Sema::TDK_Success;
3762}
Douglas Gregor05155d82009-08-21 23:19:43 +00003763/// \brief Deduce template arguments for a templated conversion
3764/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3765/// conversion function template specialization.
3766Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003767Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003768 QualType ToType,
3769 CXXConversionDecl *&Specialization,
3770 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003771 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003772 return TDK_Invalid;
3773
Faisal Vali2b3a3012013-10-24 23:40:02 +00003774 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003775 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3776
Faisal Vali2b3a3012013-10-24 23:40:02 +00003777 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003778
3779 // Canonicalize the types for deduction.
3780 QualType P = Context.getCanonicalType(FromType);
3781 QualType A = Context.getCanonicalType(ToType);
3782
Douglas Gregord99609a2011-03-06 09:03:20 +00003783 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003784 // If P is a reference type, the type referred to by P is used for
3785 // type deduction.
3786 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3787 P = PRef->getPointeeType();
3788
Douglas Gregord99609a2011-03-06 09:03:20 +00003789 // C++0x [temp.deduct.conv]p4:
3790 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003791 // for type deduction.
3792 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003793 A = ARef->getPointeeType().getUnqualifiedType();
3794 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003795 //
Mike Stump11289f42009-09-09 15:08:12 +00003796 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003797 else {
3798 assert(!A->isReferenceType() && "Reference types were handled above");
3799
3800 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003801 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003802 // of P for type deduction; otherwise,
3803 if (P->isArrayType())
3804 P = Context.getArrayDecayedType(P);
3805 // - If P is a function type, the pointer type produced by the
3806 // function-to-pointer standard conversion (4.3) is used in
3807 // place of P for type deduction; otherwise,
3808 else if (P->isFunctionType())
3809 P = Context.getPointerType(P);
3810 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003811 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003812 else
3813 P = P.getUnqualifiedType();
3814
Douglas Gregord99609a2011-03-06 09:03:20 +00003815 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003816 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003817 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003818 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003819 A = A.getUnqualifiedType();
3820 }
3821
Eli Friedman77dcc722012-02-08 03:07:05 +00003822 // Unevaluated SFINAE context.
3823 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003824 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003825
3826 // C++ [temp.deduct.conv]p1:
3827 // Template argument deduction is done by comparing the return
3828 // type of the template conversion function (call it P) with the
3829 // type that is required as the result of the conversion (call it
3830 // A) as described in 14.8.2.4.
3831 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003832 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003833 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003834 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003835
3836 // C++0x [temp.deduct.conv]p4:
3837 // In general, the deduction process attempts to find template
3838 // argument values that will make the deduced A identical to
3839 // A. However, there are two cases that allow a difference:
3840 unsigned TDF = 0;
3841 // - If the original A is a reference type, A can be more
3842 // cv-qualified than the deduced A (i.e., the type referred to
3843 // by the reference)
3844 if (ToType->isReferenceType())
3845 TDF |= TDF_ParamWithReferenceType;
3846 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003847 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003848 // conversion.
3849 //
3850 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3851 // both P and A are pointers or member pointers. In this case, we
3852 // just ignore cv-qualifiers completely).
3853 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003854 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003855 TDF |= TDF_IgnoreQualifiers;
3856 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003857 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3858 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003859 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003860
3861 // Create an Instantiation Scope for finalizing the operator.
3862 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003863 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003864 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003865 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003866 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3867 ConversionSpecialized, Info);
3868 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3869
3870 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003871 // to a ptr-to-function, use the deduced arguments from the conversion
3872 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003873 // e.g., int (*fp)(int) = [](auto a) { return a; };
3874 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3875
3876 // Get the return type of the destination ptr-to-function we are converting
3877 // to. This is necessary for matching the lambda call operator's return
3878 // type to that of the destination ptr-to-function's return type.
3879 assert(A->isPointerType() &&
3880 "Can only convert from lambda to ptr-to-function");
3881 const FunctionType *ToFunType =
3882 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003883 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3884
Faisal Vali2b3a3012013-10-24 23:40:02 +00003885 // Create the corresponding specializations of the call operator and
3886 // the static-invoker; and if the return type is auto,
3887 // deduce the return type and check if it matches the
3888 // DestFunctionPtrReturnType.
3889 // For instance:
3890 // auto L = [](auto a) { return f(a); };
3891 // int (*fp)(int) = L;
3892 // char (*fp2)(int) = L; <-- Not OK.
3893
3894 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3895 Specialization, Deduced, DestFunctionPtrReturnType,
3896 Info, *this);
3897 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003898 return Result;
3899}
3900
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003901/// \brief Deduce template arguments for a function template when there is
3902/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3903///
3904/// \param FunctionTemplate the function template for which we are performing
3905/// template argument deduction.
3906///
James Dennett18348b62012-06-22 08:52:37 +00003907/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003908/// arguments.
3909///
3910/// \param Specialization if template argument deduction was successful,
3911/// this will be set to the function template specialization produced by
3912/// template argument deduction.
3913///
3914/// \param Info the argument will be updated to provide additional information
3915/// about template argument deduction.
3916///
3917/// \returns the result of template argument deduction.
3918Sema::TemplateDeductionResult
3919Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003920 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003921 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003922 TemplateDeductionInfo &Info,
3923 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003924 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003925 QualType(), Specialization, Info,
3926 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003927}
3928
Richard Smith30482bc2011-02-20 03:19:35 +00003929namespace {
3930 /// Substitute the 'auto' type specifier within a type for a given replacement
3931 /// type.
3932 class SubstituteAutoTransform :
3933 public TreeTransform<SubstituteAutoTransform> {
3934 QualType Replacement;
3935 public:
Nico Weberc153d242014-07-28 00:02:09 +00003936 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3937 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3938 Replacement(Replacement) {}
3939
Richard Smith30482bc2011-02-20 03:19:35 +00003940 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3941 // If we're building the type pattern to deduce against, don't wrap the
3942 // substituted type in an AutoType. Certain template deduction rules
3943 // apply only when a template type parameter appears directly (and not if
3944 // the parameter is found through desugaring). For instance:
3945 // auto &&lref = lvalue;
3946 // must transform into "rvalue reference to T" not "rvalue reference to
3947 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003948 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003949 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003950 TemplateTypeParmTypeLoc NewTL =
3951 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003952 NewTL.setNameLoc(TL.getNameLoc());
3953 return Result;
3954 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003955 bool Dependent =
3956 !Replacement.isNull() && Replacement->isDependentType();
3957 QualType Result =
3958 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003959 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003960 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003961 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3962 NewTL.setNameLoc(TL.getNameLoc());
3963 return Result;
3964 }
3965 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003966
3967 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3968 // Lambdas never need to be transformed.
3969 return E;
3970 }
Richard Smith061f1e22013-04-30 21:23:01 +00003971
Richard Smith2a7d4812013-05-04 07:00:32 +00003972 QualType Apply(TypeLoc TL) {
3973 // Create some scratch storage for the transformed type locations.
3974 // FIXME: We're just going to throw this information away. Don't build it.
3975 TypeLocBuilder TLB;
3976 TLB.reserve(TL.getFullDataSize());
3977 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003978 }
Richard Smith30482bc2011-02-20 03:19:35 +00003979 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003980}
Richard Smith30482bc2011-02-20 03:19:35 +00003981
Richard Smith2a7d4812013-05-04 07:00:32 +00003982Sema::DeduceAutoResult
3983Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3984 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3985}
3986
Richard Smith061f1e22013-04-30 21:23:01 +00003987/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003988///
3989/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003990/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003991/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003992/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003993Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003994Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003995 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003996 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3997 if (NonPlaceholder.isInvalid())
3998 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003999 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004000 }
4001
Richard Smith2a7d4812013-05-04 07:00:32 +00004002 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004003 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004004 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004005 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004006 }
4007
Richard Smith74aeef52013-04-26 16:15:35 +00004008 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4009 // Since 'decltype(auto)' can only occur at the top of the type, we
4010 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004011 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004012 if (AT->isDecltypeAuto()) {
4013 if (isa<InitListExpr>(Init)) {
4014 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4015 return DAR_FailedAlreadyDiagnosed;
4016 }
4017
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004018 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004019 if (Deduced.isNull())
4020 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004021 // FIXME: Support a non-canonical deduced type for 'auto'.
4022 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004023 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004024 if (Result.isNull())
4025 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004026 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004027 } else if (!getLangOpts().CPlusPlus) {
4028 if (isa<InitListExpr>(Init)) {
4029 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4030 return DAR_FailedAlreadyDiagnosed;
4031 }
Richard Smith74aeef52013-04-26 16:15:35 +00004032 }
4033 }
4034
Richard Smith30482bc2011-02-20 03:19:35 +00004035 SourceLocation Loc = Init->getExprLoc();
4036
4037 LocalInstantiationScope InstScope(*this);
4038
4039 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004040 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004041 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4042 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004043 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4044 NamedDecl *TemplParamPtr = TemplParam;
James Y Knight7a22b242015-08-06 20:26:32 +00004045 FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
4046 Loc, Loc, &TemplParamPtr, Loc);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004047
Richard Smith061f1e22013-04-30 21:23:01 +00004048 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4049 assert(!FuncParam.isNull() &&
4050 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004051
4052 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004053 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004054 Deduced.resize(1);
4055 QualType InitType = Init->getType();
4056 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004057
Craig Toppere6706e42012-09-19 02:26:47 +00004058 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004059
Richard Smith74801c82012-07-08 04:13:07 +00004060 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004061 if (InitList) {
4062 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004063 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4064 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004065 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004066 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004067 }
4068 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004069 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4070 Diag(Loc, diag::err_auto_bitfield);
4071 return DAR_FailedAlreadyDiagnosed;
4072 }
4073
James Y Knight7a22b242015-08-06 20:26:32 +00004074 if (AdjustFunctionParmAndArgTypesForDeduction(
4075 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004076 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004077
James Y Knight7a22b242015-08-06 20:26:32 +00004078 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4079 FuncParam, InitType, Info, Deduced,
4080 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004081 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004082 }
Richard Smith30482bc2011-02-20 03:19:35 +00004083
Eli Friedmane4310952012-11-06 23:56:42 +00004084 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004085 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004086
Eli Friedmane4310952012-11-06 23:56:42 +00004087 QualType DeducedType = Deduced[0].getAsType();
4088
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004089 if (InitList) {
4090 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4091 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004092 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004093 }
4094
Richard Smith061f1e22013-04-30 21:23:01 +00004095 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004096 if (Result.isNull())
4097 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004098
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004099 // Check that the deduced argument type is compatible with the original
4100 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004101 if (!InitList && !Result.isNull() &&
4102 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004103 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004104 Result)) {
4105 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004106 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004107 }
4108
Sebastian Redl09edce02012-01-23 22:09:39 +00004109 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004110}
4111
Faisal Vali2b391ab2013-09-26 19:54:12 +00004112QualType Sema::SubstAutoType(QualType TypeWithAuto,
4113 QualType TypeToReplaceAuto) {
4114 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4115 TransformType(TypeWithAuto);
4116}
4117
4118TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4119 QualType TypeToReplaceAuto) {
4120 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4121 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004122}
4123
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004124void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4125 if (isa<InitListExpr>(Init))
4126 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004127 VDecl->isInitCapture()
4128 ? diag::err_init_capture_deduction_failure_from_init_list
4129 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004130 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4131 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004132 Diag(VDecl->getLocation(),
4133 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4134 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004135 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4136 << Init->getSourceRange();
4137}
4138
Richard Smith2a7d4812013-05-04 07:00:32 +00004139bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4140 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004141 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004142
4143 if (FD->getTemplateInstantiationPattern())
4144 InstantiateFunctionDefinition(Loc, FD);
4145
Alp Toker314cc812014-01-25 16:55:45 +00004146 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004147 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4148 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4149 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4150 }
4151
4152 return StillUndeduced;
4153}
4154
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004155static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004156MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004157 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004158 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004159 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
4161/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004162static void
4163AddImplicitObjectParameterType(ASTContext &Context,
4164 CXXMethodDecl *Method,
4165 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004166 // C++11 [temp.func.order]p3:
4167 // [...] The new parameter is of type "reference to cv A," where cv are
4168 // the cv-qualifiers of the function template (if any) and A is
4169 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004170 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004171 // The standard doesn't say explicitly, but we pick the appropriate kind of
4172 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004173 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4174 ArgTy = Context.getQualifiedType(ArgTy,
4175 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004176 if (Method->getRefQualifier() == RQ_RValue)
4177 ArgTy = Context.getRValueReferenceType(ArgTy);
4178 else
4179 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004180 ArgTypes.push_back(ArgTy);
4181}
4182
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004183/// \brief Determine whether the function template \p FT1 is at least as
4184/// specialized as \p FT2.
4185static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004186 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004187 FunctionTemplateDecl *FT1,
4188 FunctionTemplateDecl *FT2,
4189 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004190 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004191 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004193 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4194 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004196 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4197 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004198 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004199 Deduced.resize(TemplateParams->size());
4200
4201 // C++0x [temp.deduct.partial]p3:
4202 // The types used to determine the ordering depend on the context in which
4203 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004204 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004205 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004206 switch (TPOC) {
4207 case TPOC_Call: {
4208 // - In the context of a function call, the function parameter types are
4209 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004210 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4211 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004212
Eli Friedman3b5774a2012-09-19 23:27:04 +00004213 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004214 // [...] If only one of the function templates is a non-static
4215 // member, that function template is considered to have a new
4216 // first parameter inserted in its function parameter list. The
4217 // new parameter is of type "reference to cv A," where cv are
4218 // the cv-qualifiers of the function template (if any) and A is
4219 // the class of which the function template is a member.
4220 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004221 // Note that we interpret this to mean "if one of the function
4222 // templates is a non-static member and the other is a non-member";
4223 // otherwise, the ordering rules for static functions against non-static
4224 // functions don't make any sense.
4225 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004226 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4227 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004228 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004229
Richard Smithe5b52202013-09-11 00:52:39 +00004230 unsigned NumComparedArguments = NumCallArguments1;
4231
4232 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004233 // Compare 'this' from Method1 against first parameter from Method2.
4234 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4235 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004236 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004237 // Compare 'this' from Method2 against first parameter from Method1.
4238 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004239 }
4240
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004241 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004242 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004243 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004244 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
Douglas Gregorb837ea42011-01-11 17:34:58 +00004246 // C++ [temp.func.order]p5:
4247 // The presence of unused ellipsis and default arguments has no effect on
4248 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004249 if (Args1.size() > NumComparedArguments)
4250 Args1.resize(NumComparedArguments);
4251 if (Args2.size() > NumComparedArguments)
4252 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004253 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4254 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004255 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004256 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004258 break;
4259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004261 case TPOC_Conversion:
4262 // - In the context of a call to a conversion operator, the return types
4263 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004264 if (DeduceTemplateArgumentsByTypeMatch(
4265 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4266 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004267 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004268 return false;
4269 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004271 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004272 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004273 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004274 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4275 FD2->getType(), FD1->getType(),
4276 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004277 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 return false;
4279 break;
4280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004282 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283 // In most cases, all template parameters must have values in order for
4284 // deduction to succeed, but for partial ordering purposes a template
4285 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 // types being used for partial ordering. [ Note: a template parameter used
4287 // in a non-deduced context is considered used. -end note]
4288 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4289 for (; ArgIdx != NumArgs; ++ArgIdx)
4290 if (Deduced[ArgIdx].isNull())
4291 break;
4292
4293 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004295 // as FT2.
4296 return true;
4297 }
4298
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004299 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004300 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004301 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004302 case TPOC_Call:
4303 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4304 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004305 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004306 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004307 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004309 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004310 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4311 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004312 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004314 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004315 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004316 TemplateParams->getDepth(),
4317 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004318 break;
4319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004321 for (; ArgIdx != NumArgs; ++ArgIdx)
4322 // If this argument had no value deduced but was used in one of the types
4323 // used for partial ordering, then deduction fails.
4324 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4325 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 return true;
4328}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregorcef1a032011-01-16 16:03:23 +00004330/// \brief Determine whether this a function template whose parameter-type-list
4331/// ends with a function parameter pack.
4332static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4333 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4334 unsigned NumParams = Function->getNumParams();
4335 if (NumParams == 0)
4336 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregorcef1a032011-01-16 16:03:23 +00004338 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4339 if (!Last->isParameterPack())
4340 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
Douglas Gregorcef1a032011-01-16 16:03:23 +00004342 // Make sure that no previous parameter is a parameter pack.
4343 while (--NumParams > 0) {
4344 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4345 return false;
4346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregorcef1a032011-01-16 16:03:23 +00004348 return true;
4349}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Douglas Gregorbe999392009-09-15 16:23:51 +00004351/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004352/// to the rules of function template partial ordering (C++ [temp.func.order]).
4353///
4354/// \param FT1 the first function template
4355///
4356/// \param FT2 the second function template
4357///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358/// \param TPOC the context in which we are performing partial ordering of
4359/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004360///
Richard Smithe5b52202013-09-11 00:52:39 +00004361/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4362/// only when \c TPOC is \c TPOC_Call.
4363///
4364/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4365/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004366///
Douglas Gregorbe999392009-09-15 16:23:51 +00004367/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004368/// template is more specialized, returns NULL.
4369FunctionTemplateDecl *
4370Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4371 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004372 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004373 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004374 unsigned NumCallArguments1,
4375 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004376 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004377 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004379 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004381 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004382 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004384 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004385 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004386
Douglas Gregorcef1a032011-01-16 16:03:23 +00004387 // FIXME: This mimics what GCC implements, but doesn't match up with the
4388 // proposed resolution for core issue 692. This area needs to be sorted out,
4389 // but for now we attempt to maintain compatibility.
4390 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4391 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4392 if (Variadic1 != Variadic2)
4393 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Craig Topperc3ec1492014-05-26 06:22:03 +00004395 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004396}
Douglas Gregor9b146582009-07-08 20:55:45 +00004397
Douglas Gregor450f00842009-09-25 18:43:00 +00004398/// \brief Determine if the two templates are equivalent.
4399static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4400 if (T1 == T2)
4401 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregor450f00842009-09-25 18:43:00 +00004403 if (!T1 || !T2)
4404 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregor450f00842009-09-25 18:43:00 +00004406 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4407}
4408
4409/// \brief Retrieve the most specialized of the given function template
4410/// specializations.
4411///
John McCall58cc69d2010-01-27 01:50:18 +00004412/// \param SpecBegin the start iterator of the function template
4413/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004414///
John McCall58cc69d2010-01-27 01:50:18 +00004415/// \param SpecEnd the end iterator of the function template
4416/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004417///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004419/// diagnostic should occur.
4420///
4421/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4422/// no matching candidates.
4423///
4424/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4425/// occurs.
4426///
4427/// \param CandidateDiag partial diagnostic used for each function template
4428/// specialization that is a candidate in the ambiguous ordering. One parameter
4429/// in this diagnostic should be unbound, which will correspond to the string
4430/// describing the template arguments for the function template specialization.
4431///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004433/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004434UnresolvedSetIterator Sema::getMostSpecialized(
4435 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4436 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004437 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4438 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4439 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004440 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004441 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004442 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004443 FailedCandidates.NoteCandidates(*this, Loc);
4444 }
John McCall58cc69d2010-01-27 01:50:18 +00004445 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447
4448 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004449 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Douglas Gregor450f00842009-09-25 18:43:00 +00004451 // Find the function template that is better than all of the templates it
4452 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004453 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004455 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004456 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004457 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4458 FunctionTemplateDecl *Challenger
4459 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004460 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004461 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004462 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004463 Challenger)) {
4464 Best = I;
4465 BestTemplate = Challenger;
4466 }
4467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregor450f00842009-09-25 18:43:00 +00004469 // Make sure that the "best" function template is more specialized than all
4470 // of the others.
4471 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004472 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4473 FunctionTemplateDecl *Challenger
4474 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004475 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004477 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004478 BestTemplate)) {
4479 Ambiguous = true;
4480 break;
4481 }
4482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483
Douglas Gregor450f00842009-09-25 18:43:00 +00004484 if (!Ambiguous) {
4485 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004486 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregor450f00842009-09-25 18:43:00 +00004489 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004490 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004491 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492
Richard Smithb875c432013-05-04 01:51:08 +00004493 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004494 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4495 PartialDiagnostic PD = CandidateDiag;
4496 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004497 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004498 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004499 if (!TargetType.isNull())
4500 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4501 TargetType);
4502 Diag((*I)->getLocation(), PD);
4503 }
Richard Smithb875c432013-05-04 01:51:08 +00004504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
John McCall58cc69d2010-01-27 01:50:18 +00004506 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004507}
4508
Douglas Gregorbe999392009-09-15 16:23:51 +00004509/// \brief Returns the more specialized class template partial specialization
4510/// according to the rules of partial ordering of class template partial
4511/// specializations (C++ [temp.class.order]).
4512///
4513/// \param PS1 the first class template partial specialization
4514///
4515/// \param PS2 the second class template partial specialization
4516///
4517/// \returns the more specialized class template partial specialization. If
4518/// neither partial specialization is more specialized, returns NULL.
4519ClassTemplatePartialSpecializationDecl *
4520Sema::getMoreSpecializedPartialSpecialization(
4521 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004522 ClassTemplatePartialSpecializationDecl *PS2,
4523 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004524 // C++ [temp.class.order]p1:
4525 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526 // specialized as the second if, given the following rewrite to two
4527 // function templates, the first function template is at least as
4528 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004529 // templates (14.6.6.2):
4530 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531 // first partial specialization and has a single function parameter
4532 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004533 // arguments of the first partial specialization, and
4534 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 // second partial specialization and has a single function parameter
4536 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004537 // arguments of the second partial specialization.
4538 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004539 // Rather than synthesize function templates, we merely perform the
4540 // equivalent partial ordering by performing deduction directly on
4541 // the template arguments of the class template partial
4542 // specializations. This computation is slightly simpler than the
4543 // general problem of function template partial ordering, because
4544 // class template partial specializations are more constrained. We
4545 // know that every template parameter is deducible from the class
4546 // template partial specialization's template arguments, for
4547 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004548 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004549 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004550
4551 QualType PT1 = PS1->getInjectedSpecializationType();
4552 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553
Douglas Gregorbe999392009-09-15 16:23:51 +00004554 // Determine whether PS1 is at least as specialized as PS2
4555 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004556 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4557 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004558 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004559 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004560 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004561 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004562 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004563 Better1 = !::FinishTemplateArgumentDeduction(
4564 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4565 }
4566
4567 // Determine whether PS2 is at least as specialized as PS1
4568 Deduced.clear();
4569 Deduced.resize(PS1->getTemplateParameters()->size());
4570 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4571 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004572 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004573 if (Better2) {
4574 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4575 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004576 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004577 Better2 = !::FinishTemplateArgumentDeduction(
4578 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4579 }
4580
4581 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004582 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004583
4584 return Better1 ? PS1 : PS2;
4585}
4586
Larisse Voufo30616382013-08-23 22:21:36 +00004587/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4588/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4589/// VarTemplate(Partial)SpecializationDecl with a new data
4590/// structure Template(Partial)SpecializationDecl, and
4591/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004592VarTemplatePartialSpecializationDecl *
4593Sema::getMoreSpecializedPartialSpecialization(
4594 VarTemplatePartialSpecializationDecl *PS1,
4595 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4596 SmallVector<DeducedTemplateArgument, 4> Deduced;
4597 TemplateDeductionInfo Info(Loc);
4598
Richard Smithf04fd0b2013-12-12 23:14:16 +00004599 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004600 "the partial specializations being compared should specialize"
4601 " the same template.");
4602 TemplateName Name(PS1->getSpecializedTemplate());
4603 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4604 QualType PT1 = Context.getTemplateSpecializationType(
4605 CanonTemplate, PS1->getTemplateArgs().data(),
4606 PS1->getTemplateArgs().size());
4607 QualType PT2 = Context.getTemplateSpecializationType(
4608 CanonTemplate, PS2->getTemplateArgs().data(),
4609 PS2->getTemplateArgs().size());
4610
4611 // Determine whether PS1 is at least as specialized as PS2
4612 Deduced.resize(PS2->getTemplateParameters()->size());
4613 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4614 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004615 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004616 if (Better1) {
4617 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4618 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004619 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4621 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004622 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregorbe999392009-09-15 16:23:51 +00004625 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004626 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004627 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004628 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4629 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004630 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004631 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004632 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004633 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004634 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4636 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004637 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregorbe999392009-09-15 16:23:51 +00004640 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004641 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642
Douglas Gregorbe999392009-09-15 16:23:51 +00004643 return Better1? PS1 : PS2;
4644}
4645
Mike Stump11289f42009-09-09 15:08:12 +00004646static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004647MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004648 const TemplateArgument &TemplateArg,
4649 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004650 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004651 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004652
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004653/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004654/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004655static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004656MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004657 const Expr *E,
4658 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004659 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004660 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004661 // We can deduce from a pack expansion.
4662 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4663 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Richard Smith34349002012-07-09 03:07:20 +00004665 // Skip through any implicit casts we added while type-checking, and any
4666 // substitutions performed by template alias expansion.
4667 while (1) {
4668 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4669 E = ICE->getSubExpr();
4670 else if (const SubstNonTypeTemplateParmExpr *Subst =
4671 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4672 E = Subst->getReplacement();
4673 else
4674 break;
4675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
4677 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004678 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004679 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004680 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004681 return;
4682
Mike Stump11289f42009-09-09 15:08:12 +00004683 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004684 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4685 if (!NTTP)
4686 return;
4687
Douglas Gregor21610382009-10-29 00:04:11 +00004688 if (NTTP->getDepth() == Depth)
4689 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004690}
4691
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004692/// \brief Mark the template parameters that are used by the given
4693/// nested name specifier.
4694static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004695MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004696 NestedNameSpecifier *NNS,
4697 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004698 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004699 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004700 if (!NNS)
4701 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004703 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004704 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004705 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004706 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004707}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004709/// \brief Mark the template parameters that are used by the given
4710/// template name.
4711static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004712MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004713 TemplateName Name,
4714 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004715 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004716 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004717 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4718 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004719 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4720 if (TTP->getDepth() == Depth)
4721 Used[TTP->getIndex()] = true;
4722 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004723 return;
4724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004726 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004727 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004728 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004729 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004730 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004731 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732}
4733
4734/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004735/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004736static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004737MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004738 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004739 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004740 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741 if (T.isNull())
4742 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregor91772d12009-06-13 00:26:55 +00004744 // Non-dependent types have nothing deducible
4745 if (!T->isDependentType())
4746 return;
4747
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004748 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004749 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004750 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004751 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 cast<PointerType>(T)->getPointeeType(),
4753 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004754 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004755 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004756 break;
4757
4758 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004759 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 cast<BlockPointerType>(T)->getPointeeType(),
4761 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004762 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004763 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004764 break;
4765
4766 case Type::LValueReference:
4767 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004768 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004769 cast<ReferenceType>(T)->getPointeeType(),
4770 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004771 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004772 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004773 break;
4774
4775 case Type::MemberPointer: {
4776 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004777 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004778 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004779 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004780 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004781 break;
4782 }
4783
4784 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004785 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004786 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004787 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004788 // Fall through to check the element type
4789
4790 case Type::ConstantArray:
4791 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004792 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004793 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004794 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004795 break;
4796
4797 case Type::Vector:
4798 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004799 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004800 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004801 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004802 break;
4803
Douglas Gregor758a8692009-06-17 21:51:59 +00004804 case Type::DependentSizedExtVector: {
4805 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004806 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004807 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004808 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004809 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004810 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004811 break;
4812 }
4813
Douglas Gregor91772d12009-06-13 00:26:55 +00004814 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004815 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004816 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4817 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004818 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4819 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004820 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004821 break;
4822 }
4823
Douglas Gregor21610382009-10-29 00:04:11 +00004824 case Type::TemplateTypeParm: {
4825 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4826 if (TTP->getDepth() == Depth)
4827 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004828 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004829 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004830
Douglas Gregorfb322d82011-01-14 05:11:40 +00004831 case Type::SubstTemplateTypeParmPack: {
4832 const SubstTemplateTypeParmPackType *Subst
4833 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004835 QualType(Subst->getReplacedParameter(), 0),
4836 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004837 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004838 OnlyDeduced, Depth, Used);
4839 break;
4840 }
4841
John McCall2408e322010-04-27 00:57:59 +00004842 case Type::InjectedClassName:
4843 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4844 // fall through
4845
Douglas Gregor91772d12009-06-13 00:26:55 +00004846 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004847 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004848 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004849 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004850 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851
Douglas Gregord0ad2942010-12-23 01:24:45 +00004852 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004853 // If the template argument list of P contains a pack expansion that is
4854 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004855 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004857 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4858 break;
4859
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004860 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004861 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004862 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004863 break;
4864 }
4865
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004866 case Type::Complex:
4867 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004868 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004869 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004870 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 break;
4872
Eli Friedman0dfb8892011-10-06 23:00:33 +00004873 case Type::Atomic:
4874 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004875 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004876 cast<AtomicType>(T)->getValueType(),
4877 OnlyDeduced, Depth, Used);
4878 break;
4879
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004880 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004881 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004882 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004883 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004884 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004885 break;
4886
John McCallc392f372010-06-11 00:33:02 +00004887 case Type::DependentTemplateSpecialization: {
4888 const DependentTemplateSpecializationType *Spec
4889 = cast<DependentTemplateSpecializationType>(T);
4890 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004891 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004892 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893
Douglas Gregord0ad2942010-12-23 01:24:45 +00004894 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895 // If the template argument list of P contains a pack expansion that is not
4896 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004897 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004899 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4900 break;
4901
John McCallc392f372010-06-11 00:33:02 +00004902 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004903 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004904 Used);
4905 break;
4906 }
4907
John McCallbd8d9bd2010-03-01 23:49:17 +00004908 case Type::TypeOf:
4909 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004910 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004911 cast<TypeOfType>(T)->getUnderlyingType(),
4912 OnlyDeduced, Depth, Used);
4913 break;
4914
4915 case Type::TypeOfExpr:
4916 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004917 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004918 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4919 OnlyDeduced, Depth, Used);
4920 break;
4921
4922 case Type::Decltype:
4923 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004924 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004925 cast<DecltypeType>(T)->getUnderlyingExpr(),
4926 OnlyDeduced, Depth, Used);
4927 break;
4928
Alexis Hunte852b102011-05-24 22:41:36 +00004929 case Type::UnaryTransform:
4930 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004931 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004932 cast<UnaryTransformType>(T)->getUnderlyingType(),
4933 OnlyDeduced, Depth, Used);
4934 break;
4935
Douglas Gregord2fa7662010-12-20 02:24:11 +00004936 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004937 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004938 cast<PackExpansionType>(T)->getPattern(),
4939 OnlyDeduced, Depth, Used);
4940 break;
4941
Richard Smith30482bc2011-02-20 03:19:35 +00004942 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004943 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004944 cast<AutoType>(T)->getDeducedType(),
4945 OnlyDeduced, Depth, Used);
4946
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004947 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004948 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004949 case Type::VariableArray:
4950 case Type::FunctionNoProto:
4951 case Type::Record:
4952 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004953 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004954 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004955 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004956 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004957#define TYPE(Class, Base)
4958#define ABSTRACT_TYPE(Class, Base)
4959#define DEPENDENT_TYPE(Class, Base)
4960#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4961#include "clang/AST/TypeNodes.def"
4962 break;
4963 }
4964}
4965
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004966/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004967/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004968static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004969MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004970 const TemplateArgument &TemplateArg,
4971 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004972 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004973 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004974 switch (TemplateArg.getKind()) {
4975 case TemplateArgument::Null:
4976 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004977 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004978 break;
Mike Stump11289f42009-09-09 15:08:12 +00004979
Eli Friedmanb826a002012-09-26 02:36:12 +00004980 case TemplateArgument::NullPtr:
4981 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4982 Depth, Used);
4983 break;
4984
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004986 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004987 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004988 break;
4989
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004990 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004991 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004992 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004994 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004995 break;
4996
4997 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004998 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004999 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Anders Carlssonbc343912009-06-15 17:04:53 +00005002 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005003 for (const auto &P : TemplateArg.pack_elements())
5004 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005005 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005006 }
5007}
5008
James Dennett41725122012-06-22 10:16:05 +00005009/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005010/// template argument list.
5011///
5012/// \param TemplateArgs the template argument list from which template
5013/// parameters will be deduced.
5014///
James Dennett41725122012-06-22 10:16:05 +00005015/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005016/// to indicate when the corresponding template parameter will be
5017/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005018void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005019Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005020 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005021 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005022 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 // If the template argument list of P contains a pack expansion that is not
5024 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005025 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005027 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5028 return;
5029
Douglas Gregor91772d12009-06-13 00:26:55 +00005030 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005031 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005032 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005033}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005034
5035/// \brief Marks all of the template parameters that will be deduced by a
5036/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005037void Sema::MarkDeducedTemplateParameters(
5038 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5039 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005041 = FunctionTemplate->getTemplateParameters();
5042 Deduced.clear();
5043 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Douglas Gregorce23bae2009-09-18 23:21:38 +00005045 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5046 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005047 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005048 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005049}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005050
5051bool hasDeducibleTemplateParameters(Sema &S,
5052 FunctionTemplateDecl *FunctionTemplate,
5053 QualType T) {
5054 if (!T->isDependentType())
5055 return false;
5056
5057 TemplateParameterList *TemplateParams
5058 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005059 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005060 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005061 Deduced);
5062
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005063 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005064}