blob: 2311b2b7447d0fdc74465abddd662d3c3cedab92 [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
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000106DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000107 const TemplateArgument *Params, unsigned NumParams,
108 const TemplateArgument *Args, unsigned NumArgs,
109 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000110 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
111 bool NumberOfArgumentsMustMatch);
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
Richard Smith38175a22016-09-28 22:08:38 +0000288/// from the given integral constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000289static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
290 Sema &S, NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
291 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
292 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000293 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000294 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000295
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000296 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
297 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000298 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000299 Deduced[NTTP->getIndex()],
300 NewDeduced);
301 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000302 Info.Param = NTTP;
303 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000309 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000310}
311
Mike Stump11289f42009-09-09 15:08:12 +0000312/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000313/// from the given null pointer template argument type.
314static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
315 Sema &S, NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
316 TemplateDeductionInfo &Info,
317 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
318 Expr *Value =
319 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
320 S.Context.NullPtrTy, NTTP->getLocation()),
321 NullPtrType, CK_NullToPointer)
322 .get();
323 DeducedTemplateArgument NewDeduced(Value);
324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
325 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
326
327 if (Result.isNull()) {
328 Info.Param = NTTP;
329 Info.FirstArg = Deduced[NTTP->getIndex()];
330 Info.SecondArg = NewDeduced;
331 return Sema::TDK_Inconsistent;
332 }
333
334 Deduced[NTTP->getIndex()] = Result;
335 return Sema::TDK_Success;
336}
337
338/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000339/// from the given type- or value-dependent expression.
340///
341/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000342static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000343DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000344 NonTypeTemplateParmDecl *NTTP,
345 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000346 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000348 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000349 "Cannot deduce non-type template argument with depth > 0");
350 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
351 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000352
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000353 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000354 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
355 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000356 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000358 if (Result.isNull()) {
359 Info.Param = NTTP;
360 Info.FirstArg = Deduced[NTTP->getIndex()];
361 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000365 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000366 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000367}
368
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000369/// \brief Deduce the value of the given non-type template parameter
370/// from the given declaration.
371///
372/// \returns true if deduction succeeded, false otherwise.
373static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000374DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000375 NonTypeTemplateParmDecl *NTTP,
376 ValueDecl *D,
377 TemplateDeductionInfo &Info,
378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000379 assert(NTTP->getDepth() == 0 &&
380 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000381
Craig Topperc3ec1492014-05-26 06:22:03 +0000382 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000383 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000384 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000386 Deduced[NTTP->getIndex()],
387 NewDeduced);
388 if (Result.isNull()) {
389 Info.Param = NTTP;
390 Info.FirstArg = Deduced[NTTP->getIndex()];
391 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000395 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000396 return Sema::TDK_Success;
397}
398
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000399static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000400DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000401 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000402 TemplateName Param,
403 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000404 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000405 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000406 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000407 if (!ParamDecl) {
408 // The parameter type is dependent and is not a template template parameter,
409 // so there is nothing that we can deduce.
410 return Sema::TDK_Success;
411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000412
Douglas Gregoradee3e32009-11-11 23:06:43 +0000413 if (TemplateTemplateParmDecl *TempParam
414 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000415 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000417 Deduced[TempParam->getIndex()],
418 NewDeduced);
419 if (Result.isNull()) {
420 Info.Param = TempParam;
421 Info.FirstArg = Deduced[TempParam->getIndex()];
422 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000426 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429
Douglas Gregoradee3e32009-11-11 23:06:43 +0000430 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000431 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000432 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregoradee3e32009-11-11 23:06:43 +0000434 // Mismatch of non-dependent template parameter to argument.
435 Info.FirstArg = TemplateArgument(Param);
436 Info.SecondArg = TemplateArgument(Arg);
437 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000438}
439
Mike Stump11289f42009-09-09 15:08:12 +0000440/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000441/// type (which is a template-id) with the template argument type.
442///
Chandler Carruthc1263112010-02-07 21:33:28 +0000443/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444///
445/// \param TemplateParams the template parameters that we are deducing
446///
447/// \param Param the parameter type
448///
449/// \param Arg the argument type
450///
451/// \param Info information about the template argument deduction itself
452///
453/// \param Deduced the deduced template arguments
454///
455/// \returns the result of template argument deduction so far. Note that a
456/// "success" result means that template argument deduction has not yet failed,
457/// but it may still fail, later, for other reasons.
458static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000459DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000460 TemplateParameterList *TemplateParams,
461 const TemplateSpecializationType *Param,
462 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000463 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000464 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000465 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000466
Douglas Gregore81f3e72009-07-07 23:09:34 +0000467 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000468 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000469 = dyn_cast<TemplateSpecializationType>(Arg)) {
470 // Perform template argument deduction for the template name.
471 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000472 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000473 Param->getTemplateName(),
474 SpecArg->getTemplateName(),
475 Info, Deduced))
476 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000477
Mike Stump11289f42009-09-09 15:08:12 +0000478
Douglas Gregore81f3e72009-07-07 23:09:34 +0000479 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000480 // argument. Ignore any missing/extra arguments, since they could be
481 // filled in by default arguments.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000482 return DeduceTemplateArguments(S, TemplateParams, Param->getArgs(),
483 Param->getNumArgs(), SpecArg->getArgs(),
484 SpecArg->getNumArgs(), Info, Deduced,
485 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregore81f3e72009-07-07 23:09:34 +0000488 // If the argument type is a class template specialization, we
489 // perform template argument deduction using its template
490 // arguments.
491 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000492 if (!RecordArg) {
493 Info.FirstArg = TemplateArgument(QualType(Param, 0));
494 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000495 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
498 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000499 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000500 if (!SpecArg) {
501 Info.FirstArg = TemplateArgument(QualType(Param, 0));
502 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000503 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 // Perform template argument deduction for the template name.
507 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000508 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000509 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 Param->getTemplateName(),
511 TemplateName(SpecArg->getSpecializedTemplate()),
512 Info, Deduced))
513 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregor7baabef2010-12-22 18:17:10 +0000515 // Perform template argument deduction for the template arguments.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000516 return DeduceTemplateArguments(
517 S, TemplateParams, Param->getArgs(), Param->getNumArgs(),
518 SpecArg->getTemplateArgs().data(), SpecArg->getTemplateArgs().size(),
519 Info, Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000520}
521
John McCall08569062010-08-28 22:14:41 +0000522/// \brief Determines whether the given type is an opaque type that
523/// might be more qualified when instantiated.
524static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
525 switch (T->getTypeClass()) {
526 case Type::TypeOfExpr:
527 case Type::TypeOf:
528 case Type::DependentName:
529 case Type::Decltype:
530 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000531 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000532 return true;
533
534 case Type::ConstantArray:
535 case Type::IncompleteArray:
536 case Type::VariableArray:
537 case Type::DependentSizedArray:
538 return IsPossiblyOpaquelyQualifiedType(
539 cast<ArrayType>(T)->getElementType());
540
541 default:
542 return false;
543 }
544}
545
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000546/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000548getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000549 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
550 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregor5499af42011-01-05 23:12:31 +0000552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
553 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor5499af42011-01-05 23:12:31 +0000555 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
556 return std::make_pair(TTP->getDepth(), TTP->getIndex());
557}
558
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000559/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000560static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000561getDepthAndIndex(UnexpandedParameterPack UPP) {
562 if (const TemplateTypeParmType *TTP
563 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
564 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000566 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
567}
568
Douglas Gregor5499af42011-01-05 23:12:31 +0000569/// \brief Helper function to build a TemplateParameter when we don't
570/// know its type statically.
571static TemplateParameter makeTemplateParameter(Decl *D) {
572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
573 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000574 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000575 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregor5499af42011-01-05 23:12:31 +0000577 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
578}
579
Richard Smith0a80d572014-05-29 01:12:14 +0000580/// A pack that we're currently deducing.
581struct clang::DeducedPack {
582 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000583
Richard Smith0a80d572014-05-29 01:12:14 +0000584 // The index of the pack.
585 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Richard Smith0a80d572014-05-29 01:12:14 +0000587 // The old value of the pack before we started deducing it.
588 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000589
Richard Smith0a80d572014-05-29 01:12:14 +0000590 // A deferred value of this pack from an inner deduction, that couldn't be
591 // deduced because this deduction hadn't happened yet.
592 DeducedTemplateArgument DeferredDeduction;
593
594 // The new value of the pack.
595 SmallVector<DeducedTemplateArgument, 4> New;
596
597 // The outer deduction for this pack, if any.
598 DeducedPack *Outer;
599};
600
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000601namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000602/// A scope in which we're performing pack deduction.
603class PackDeductionScope {
604public:
605 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
606 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
607 TemplateDeductionInfo &Info, TemplateArgument Pattern)
608 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
609 // Compute the set of template parameter indices that correspond to
610 // parameter packs expanded by the pack expansion.
611 {
612 llvm::SmallBitVector SawIndices(TemplateParams->size());
613 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
614 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
615 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
616 unsigned Depth, Index;
617 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
618 if (Depth == 0 && !SawIndices[Index]) {
619 SawIndices[Index] = true;
620
621 // Save the deduced template argument for the parameter pack expanded
622 // by this pack expansion, then clear out the deduction.
623 DeducedPack Pack(Index);
624 Pack.Saved = Deduced[Index];
625 Deduced[Index] = TemplateArgument();
626
627 Packs.push_back(Pack);
628 }
629 }
630 }
631 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
632
633 for (auto &Pack : Packs) {
634 if (Info.PendingDeducedPacks.size() > Pack.Index)
635 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
636 else
637 Info.PendingDeducedPacks.resize(Pack.Index + 1);
638 Info.PendingDeducedPacks[Pack.Index] = &Pack;
639
640 if (S.CurrentInstantiationScope) {
641 // If the template argument pack was explicitly specified, add that to
642 // the set of deduced arguments.
643 const TemplateArgument *ExplicitArgs;
644 unsigned NumExplicitArgs;
645 NamedDecl *PartiallySubstitutedPack =
646 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
647 &ExplicitArgs, &NumExplicitArgs);
648 if (PartiallySubstitutedPack &&
649 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
650 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
651 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000652 }
653 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000654
Richard Smith0a80d572014-05-29 01:12:14 +0000655 ~PackDeductionScope() {
656 for (auto &Pack : Packs)
657 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Richard Smith0a80d572014-05-29 01:12:14 +0000660 /// Move to deducing the next element in each pack that is being deduced.
661 void nextPackElement() {
662 // Capture the deduced template arguments for each parameter pack expanded
663 // by this pack expansion, add them to the list of arguments we've deduced
664 // for that pack, then clear out the deduced argument.
665 for (auto &Pack : Packs) {
666 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
667 if (!DeducedArg.isNull()) {
668 Pack.New.push_back(DeducedArg);
669 DeducedArg = DeducedTemplateArgument();
670 }
671 }
672 }
673
674 /// \brief Finish template argument deduction for a set of argument packs,
675 /// producing the argument packs and checking for consistency with prior
676 /// deductions.
677 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
678 // Build argument packs for each of the parameter packs expanded by this
679 // pack expansion.
680 for (auto &Pack : Packs) {
681 // Put back the old value for this pack.
682 Deduced[Pack.Index] = Pack.Saved;
683
684 // Build or find a new value for this pack.
685 DeducedTemplateArgument NewPack;
686 if (HasAnyArguments && Pack.New.empty()) {
687 if (Pack.DeferredDeduction.isNull()) {
688 // We were not able to deduce anything for this parameter pack
689 // (because it only appeared in non-deduced contexts), so just
690 // restore the saved argument pack.
691 continue;
692 }
693
694 NewPack = Pack.DeferredDeduction;
695 Pack.DeferredDeduction = TemplateArgument();
696 } else if (Pack.New.empty()) {
697 // If we deduced an empty argument pack, create it now.
698 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
699 } else {
700 TemplateArgument *ArgumentPack =
701 new (S.Context) TemplateArgument[Pack.New.size()];
702 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
703 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000704 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000705 Pack.New[0].wasDeducedFromArrayBound());
706 }
707
708 // Pick where we're going to put the merged pack.
709 DeducedTemplateArgument *Loc;
710 if (Pack.Outer) {
711 if (Pack.Outer->DeferredDeduction.isNull()) {
712 // Defer checking this pack until we have a complete pack to compare
713 // it against.
714 Pack.Outer->DeferredDeduction = NewPack;
715 continue;
716 }
717 Loc = &Pack.Outer->DeferredDeduction;
718 } else {
719 Loc = &Deduced[Pack.Index];
720 }
721
722 // Check the new pack matches any previous value.
723 DeducedTemplateArgument OldPack = *Loc;
724 DeducedTemplateArgument Result =
725 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
726
727 // If we deferred a deduction of this pack, check that one now too.
728 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
729 OldPack = Result;
730 NewPack = Pack.DeferredDeduction;
731 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
732 }
733
734 if (Result.isNull()) {
735 Info.Param =
736 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
737 Info.FirstArg = OldPack;
738 Info.SecondArg = NewPack;
739 return Sema::TDK_Inconsistent;
740 }
741
742 *Loc = Result;
743 }
744
745 return Sema::TDK_Success;
746 }
747
748private:
749 Sema &S;
750 TemplateParameterList *TemplateParams;
751 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
752 TemplateDeductionInfo &Info;
753
754 SmallVector<DeducedPack, 2> Packs;
755};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000756} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000757
Douglas Gregor5499af42011-01-05 23:12:31 +0000758/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759/// types to the list of argument types, as in the parameter-type-lists of
760/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000761///
762/// \param S The semantic analysis object within which we are deducing
763///
764/// \param TemplateParams The template parameters that we are deducing
765///
766/// \param Params The list of parameter types
767///
768/// \param NumParams The number of types in \c Params
769///
770/// \param Args The list of argument types
771///
772/// \param NumArgs The number of types in \c Args
773///
774/// \param Info information about the template argument deduction itself
775///
776/// \param Deduced the deduced template arguments
777///
778/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
779/// how template argument deduction is performed.
780///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000781/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000783/// (C++0x [temp.deduct.partial]).
784///
Douglas Gregor5499af42011-01-05 23:12:31 +0000785/// \returns the result of template argument deduction so far. Note that a
786/// "success" result means that template argument deduction has not yet failed,
787/// but it may still fail, later, for other reasons.
788static Sema::TemplateDeductionResult
789DeduceTemplateArguments(Sema &S,
790 TemplateParameterList *TemplateParams,
791 const QualType *Params, unsigned NumParams,
792 const QualType *Args, unsigned NumArgs,
793 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000794 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000795 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000796 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000797 // Fast-path check to see if we have too many/too few arguments.
798 if (NumParams != NumArgs &&
799 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
800 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000801 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor5499af42011-01-05 23:12:31 +0000803 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804 // Similarly, if P has a form that contains (T), then each parameter type
805 // Pi of the respective parameter-type- list of P is compared with the
806 // corresponding parameter type Ai of the corresponding parameter-type-list
807 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000808 unsigned ArgIdx = 0, ParamIdx = 0;
809 for (; ParamIdx != NumParams; ++ParamIdx) {
810 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000812 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
813 if (!Expansion) {
814 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815
Douglas Gregor5499af42011-01-05 23:12:31 +0000816 // Make sure we have an argument.
817 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000818 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000820 if (isa<PackExpansionType>(Args[ArgIdx])) {
821 // C++0x [temp.deduct.type]p22:
822 // If the original function parameter associated with A is a function
823 // parameter pack and the function parameter associated with P is not
824 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000825 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000829 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
830 Params[ParamIdx], Args[ArgIdx],
831 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000832 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000833 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor5499af42011-01-05 23:12:31 +0000835 ++ArgIdx;
836 continue;
837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000839 // C++0x [temp.deduct.type]p5:
840 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000842 // parameter-declaration-clause.
843 if (ParamIdx + 1 < NumParams)
844 return Sema::TDK_Success;
845
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000850 // comparison deduces template arguments for subsequent positions in the
851 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852
Douglas Gregor5499af42011-01-05 23:12:31 +0000853 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000854 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 bool HasAnyArguments = false;
857 for (; ArgIdx < NumArgs; ++ArgIdx) {
858 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
Douglas Gregor5499af42011-01-05 23:12:31 +0000860 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000862 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
863 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000864 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866
Richard Smith0a80d572014-05-29 01:12:14 +0000867 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869
Douglas Gregor5499af42011-01-05 23:12:31 +0000870 // Build argument packs for each of the parameter packs expanded by this
871 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000872 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000873 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875
Douglas Gregor5499af42011-01-05 23:12:31 +0000876 // Make sure we don't have any extra arguments.
877 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000878 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 return Sema::TDK_Success;
881}
882
Douglas Gregor1d684c22011-04-28 00:56:09 +0000883/// \brief Determine whether the parameter has qualifiers that are either
884/// inconsistent with or a superset of the argument's qualifiers.
885static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
886 QualType ArgType) {
887 Qualifiers ParamQs = ParamType.getQualifiers();
888 Qualifiers ArgQs = ArgType.getQualifiers();
889
890 if (ParamQs == ArgQs)
891 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000892
Douglas Gregor1d684c22011-04-28 00:56:09 +0000893 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000894 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000895 ParamQs.hasObjCGCAttr())
896 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000897
Douglas Gregor1d684c22011-04-28 00:56:09 +0000898 // Mismatched (but not missing) address spaces.
899 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
900 ParamQs.hasAddressSpace())
901 return true;
902
John McCall31168b02011-06-15 23:02:42 +0000903 // Mismatched (but not missing) Objective-C lifetime qualifiers.
904 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
905 ParamQs.hasObjCLifetime())
906 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000907
Douglas Gregor1d684c22011-04-28 00:56:09 +0000908 // CVR qualifier superset.
909 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
910 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
911 == ParamQs.getCVRQualifiers());
912}
913
Douglas Gregor19a41f12013-04-17 08:45:07 +0000914/// \brief Compare types for equality with respect to possibly compatible
915/// function types (noreturn adjustment, implicit calling conventions). If any
916/// of parameter and argument is not a function, just perform type comparison.
917///
918/// \param Param the template parameter type.
919///
920/// \param Arg the argument type.
921bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
922 CanQualType Arg) {
923 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
924 *ArgFunction = Arg->getAs<FunctionType>();
925
926 // Just compare if not functions.
927 if (!ParamFunction || !ArgFunction)
928 return Param == Arg;
929
930 // Noreturn adjustment.
931 QualType AdjustedParam;
932 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
933 return Arg == Context.getCanonicalType(AdjustedParam);
934
935 // FIXME: Compatible calling conventions.
936
937 return Param == Arg;
938}
939
Douglas Gregorcceb9752009-06-26 18:27:22 +0000940/// \brief Deduce the template arguments by comparing the parameter type and
941/// the argument type (C++ [temp.deduct.type]).
942///
Chandler Carruthc1263112010-02-07 21:33:28 +0000943/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000944///
945/// \param TemplateParams the template parameters that we are deducing
946///
947/// \param ParamIn the parameter type
948///
949/// \param ArgIn the argument type
950///
951/// \param Info information about the template argument deduction itself
952///
953/// \param Deduced the deduced template arguments
954///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000955/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000956/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000957///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000958/// \param PartialOrdering Whether we're performing template argument deduction
959/// in the context of partial ordering (C++0x [temp.deduct.partial]).
960///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000961/// \returns the result of template argument deduction so far. Note that a
962/// "success" result means that template argument deduction has not yet failed,
963/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000964static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000965DeduceTemplateArgumentsByTypeMatch(Sema &S,
966 TemplateParameterList *TemplateParams,
967 QualType ParamIn, QualType ArgIn,
968 TemplateDeductionInfo &Info,
969 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
970 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000971 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000972 // We only want to look at the canonical types, since typedefs and
973 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000974 QualType Param = S.Context.getCanonicalType(ParamIn);
975 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000976
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000977 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000979 if (const PackExpansionType *ArgExpansion
980 = dyn_cast<PackExpansionType>(Arg))
981 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982
Douglas Gregorb837ea42011-01-11 17:34:58 +0000983 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000984 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 // Before the partial ordering is done, certain transformations are
986 // performed on the types used for partial ordering:
987 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000988 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
989 if (ParamRef)
990 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991
Douglas Gregorb837ea42011-01-11 17:34:58 +0000992 // - If A is a reference type, A is replaced by the type referred to.
993 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
994 if (ArgRef)
995 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Richard Smithed563c22015-02-20 04:45:22 +0000997 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
998 // C++11 [temp.deduct.partial]p9:
999 // If, for a given type, deduction succeeds in both directions (i.e.,
1000 // the types are identical after the transformations above) and both
1001 // P and A were reference types [...]:
1002 // - if [one type] was an lvalue reference and [the other type] was
1003 // not, [the other type] is not considered to be at least as
1004 // specialized as [the first type]
1005 // - if [one type] is more cv-qualified than [the other type],
1006 // [the other type] is not considered to be at least as specialized
1007 // as [the first type]
1008 // Objective-C ARC adds:
1009 // - [one type] has non-trivial lifetime, [the other type] has
1010 // __unsafe_unretained lifetime, and the types are otherwise
1011 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001012 //
Richard Smithed563c22015-02-20 04:45:22 +00001013 // A is "considered to be at least as specialized" as P iff deduction
1014 // succeeds, so we model this as a deduction failure. Note that
1015 // [the first type] is P and [the other type] is A here; the standard
1016 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001017 Qualifiers ParamQuals = Param.getQualifiers();
1018 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001019 if ((ParamRef->isLValueReferenceType() &&
1020 !ArgRef->isLValueReferenceType()) ||
1021 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1022 (ParamQuals.hasNonTrivialObjCLifetime() &&
1023 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1024 ParamQuals.withoutObjCLifetime() ==
1025 ArgQuals.withoutObjCLifetime())) {
1026 Info.FirstArg = TemplateArgument(ParamIn);
1027 Info.SecondArg = TemplateArgument(ArgIn);
1028 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001029 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031
Richard Smithed563c22015-02-20 04:45:22 +00001032 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001033 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001035 // version of P.
1036 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001038 // version of A.
1039 Arg = Arg.getUnqualifiedType();
1040 } else {
1041 // C++0x [temp.deduct.call]p4 bullet 1:
1042 // - If the original P is a reference type, the deduced A (i.e., the type
1043 // referred to by the reference) can be more cv-qualified than the
1044 // transformed A.
1045 if (TDF & TDF_ParamWithReferenceType) {
1046 Qualifiers Quals;
1047 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1048 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001049 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001050 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052
Douglas Gregor85f240c2011-01-25 17:19:08 +00001053 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1054 // C++0x [temp.deduct.type]p10:
1055 // If P and A are function types that originated from deduction when
1056 // taking the address of a function template (14.8.2.2) or when deducing
1057 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058 // Ai are parameters of the top-level parameter-type-list of P and A,
1059 // respectively, Pi is adjusted if it is an rvalue reference to a
1060 // cv-unqualified template parameter and Ai is an lvalue reference, in
1061 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001062 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1063 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001064 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001065 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Douglas Gregor85f240c2011-01-25 17:19:08 +00001067 if (const RValueReferenceType *ParamRef
1068 = Param->getAs<RValueReferenceType>()) {
1069 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1070 !ParamRef->getPointeeType().getQualifiers())
1071 if (Arg->isLValueReferenceType())
1072 Param = ParamRef->getPointeeType();
1073 }
1074 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001076
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001077 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001078 // A template type argument T, a template template argument TT or a
1079 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001080 // the following forms:
1081 //
1082 // T
1083 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001084 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001085 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001086 // Just skip any attempts to deduce from a placeholder type.
1087 if (Arg->isPlaceholderType())
1088 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001089
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001090 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001091 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregor60454822009-07-22 20:02:25 +00001093 // If the argument type is an array type, move the qualifiers up to the
1094 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001095 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001096 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001097 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001098 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001099 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001100 RecanonicalizeArg = true;
1101 }
1102 }
Mike Stump11289f42009-09-09 15:08:12 +00001103
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001104 // The argument type can not be less qualified than the parameter
1105 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001106 if (!(TDF & TDF_IgnoreQualifiers) &&
1107 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001108 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001109 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001110 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001111 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001112 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001113
1114 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001115 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001116 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001117
Douglas Gregor1d684c22011-04-28 00:56:09 +00001118 // Remove any qualifiers on the parameter from the deduced type.
1119 // We checked the qualifiers for consistency above.
1120 Qualifiers DeducedQs = DeducedType.getQualifiers();
1121 Qualifiers ParamQs = Param.getQualifiers();
1122 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1123 if (ParamQs.hasObjCGCAttr())
1124 DeducedQs.removeObjCGCAttr();
1125 if (ParamQs.hasAddressSpace())
1126 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001127 if (ParamQs.hasObjCLifetime())
1128 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001129
Douglas Gregore46db902011-06-17 22:11:49 +00001130 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001131 // If template deduction would produce a lifetime qualifier on a type
1132 // that is not a lifetime type, template argument deduction fails.
1133 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1134 !DeducedType->isDependentType()) {
1135 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1136 Info.FirstArg = TemplateArgument(Param);
1137 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001138 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001139 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001140
Douglas Gregora4f2b432011-07-26 14:53:44 +00001141 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001142 // If template deduction would produce an argument type with lifetime type
1143 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001144 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001145 DeducedType->isObjCLifetimeType() &&
1146 !DeducedQs.hasObjCLifetime())
1147 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001148
Douglas Gregor1d684c22011-04-28 00:56:09 +00001149 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1150 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001151
Douglas Gregord6605db2009-07-22 21:30:48 +00001152 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001153 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001155 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001157 Deduced[Index],
1158 NewDeduced);
1159 if (Result.isNull()) {
1160 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1161 Info.FirstArg = Deduced[Index];
1162 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001166 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001167 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001168 }
1169
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001170 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001171 Info.FirstArg = TemplateArgument(ParamIn);
1172 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001173
Douglas Gregorfb322d82011-01-14 05:11:40 +00001174 // If the parameter is an already-substituted template parameter
1175 // pack, do nothing: we don't know which of its arguments to look
1176 // at, so we have to wait until all of the parameter packs in this
1177 // expansion have arguments.
1178 if (isa<SubstTemplateTypeParmPackType>(Param))
1179 return Sema::TDK_Success;
1180
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001181 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001182 CanQualType CanParam = S.Context.getCanonicalType(Param);
1183 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001184 if (!(TDF & TDF_IgnoreQualifiers)) {
1185 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001186 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001187 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001188 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001189 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001190 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001191 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001192
Douglas Gregor194ea692012-03-11 03:29:50 +00001193 // If the parameter type is not dependent, there is nothing to deduce.
1194 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001195 if (!(TDF & TDF_SkipNonDependent)) {
1196 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1197 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1198 Param != Arg;
1199 if (NonDeduced) {
1200 return Sema::TDK_NonDeducedMismatch;
1201 }
1202 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001203 return Sema::TDK_Success;
1204 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001205 } else if (!Param->isDependentType()) {
1206 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1207 ArgUnqualType = CanArg.getUnqualifiedType();
1208 bool Success = (TDF & TDF_InOverloadResolution)?
1209 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1210 ArgUnqualType) :
1211 ParamUnqualType == ArgUnqualType;
1212 if (Success)
1213 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001214 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001215
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001216 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001217 // Non-canonical types cannot appear here.
1218#define NON_CANONICAL_TYPE(Class, Base) \
1219 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1220#define TYPE(Class, Base)
1221#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001222
Douglas Gregor39c02722011-06-15 16:02:29 +00001223 case Type::TemplateTypeParm:
1224 case Type::SubstTemplateTypeParmPack:
1225 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001226
1227 // These types cannot be dependent, so simply check whether the types are
1228 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001229 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001230 case Type::VariableArray:
1231 case Type::Vector:
1232 case Type::FunctionNoProto:
1233 case Type::Record:
1234 case Type::Enum:
1235 case Type::ObjCObject:
1236 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001237 case Type::ObjCObjectPointer: {
1238 if (TDF & TDF_SkipNonDependent)
1239 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001240
Douglas Gregor194ea692012-03-11 03:29:50 +00001241 if (TDF & TDF_IgnoreQualifiers) {
1242 Param = Param.getUnqualifiedType();
1243 Arg = Arg.getUnqualifiedType();
1244 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001245
Douglas Gregor194ea692012-03-11 03:29:50 +00001246 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1247 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001248
1249 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001250 case Type::Complex:
1251 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001252 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1253 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001254 ComplexArg->getElementType(),
1255 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001256
1257 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001258
1259 // _Atomic T [extension]
1260 case Type::Atomic:
1261 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001262 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001263 cast<AtomicType>(Param)->getValueType(),
1264 AtomicArg->getValueType(),
1265 Info, Deduced, TDF);
1266
1267 return Sema::TDK_NonDeducedMismatch;
1268
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001269 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001270 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001271 QualType PointeeType;
1272 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1273 PointeeType = PointerArg->getPointeeType();
1274 } else if (const ObjCObjectPointerType *PointerArg
1275 = Arg->getAs<ObjCObjectPointerType>()) {
1276 PointeeType = PointerArg->getPointeeType();
1277 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001278 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregorfc516c92009-06-26 23:27:24 +00001281 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001282 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1283 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001284 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001285 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001288 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001289 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001290 const LValueReferenceType *ReferenceArg =
1291 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001292 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001293 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001294
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001295 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001296 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001297 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001298 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001299
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001300 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001301 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001302 const RValueReferenceType *ReferenceArg =
1303 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001304 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001305 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001307 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1308 cast<RValueReferenceType>(Param)->getPointeeType(),
1309 ReferenceArg->getPointeeType(),
1310 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001311 }
Mike Stump11289f42009-09-09 15:08:12 +00001312
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001313 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001314 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001315 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001316 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001317 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001318 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001319
John McCallf7332682010-08-19 00:20:19 +00001320 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1322 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1323 IncompleteArrayArg->getElementType(),
1324 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001325 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001326
1327 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001328 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001329 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001330 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001331 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001332 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001333
1334 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001335 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001336 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001337 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001338
John McCallf7332682010-08-19 00:20:19 +00001339 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001340 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1341 ConstantArrayParm->getElementType(),
1342 ConstantArrayArg->getElementType(),
1343 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 }
1345
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001346 // type [i]
1347 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001348 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001349 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001350 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001351
John McCallf7332682010-08-19 00:20:19 +00001352 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1353
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001354 // Check the element type of the arrays
1355 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001356 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001357 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001358 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1359 DependentArrayParm->getElementType(),
1360 ArrayArg->getElementType(),
1361 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001362 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001364 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001365 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001366 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1367 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001368 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001369
1370 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001371 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001372 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001373 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001374 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001375 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1376 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001378 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001379 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001380 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001381 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001382 if (const DependentSizedArrayType *DependentArrayArg
1383 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001384 if (DependentArrayArg->getSizeExpr())
1385 return DeduceNonTypeTemplateArgument(S, NTTP,
1386 DependentArrayArg->getSizeExpr(),
1387 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001389 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001390 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
1393 // type(*)(T)
1394 // T(*)()
1395 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001396 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001397 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001398 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001399 dyn_cast<FunctionProtoType>(Arg);
1400 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001401 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001402
1403 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001404 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001405
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001407 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001408 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001409 != FunctionProtoArg->getRefQualifier() ||
1410 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001411 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001412
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001414 if (Sema::TemplateDeductionResult Result =
1415 DeduceTemplateArgumentsByTypeMatch(
1416 S, TemplateParams, FunctionProtoParam->getReturnType(),
1417 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001418 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Alp Toker9cacbab2014-01-20 20:26:09 +00001420 return DeduceTemplateArguments(
1421 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1422 FunctionProtoParam->getNumParams(),
1423 FunctionProtoArg->param_type_begin(),
1424 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001425 }
Mike Stump11289f42009-09-09 15:08:12 +00001426
John McCalle78aac42010-03-10 03:28:59 +00001427 case Type::InjectedClassName: {
1428 // Treat a template's injected-class-name as if the template
1429 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001430 Param = cast<InjectedClassNameType>(Param)
1431 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001432 assert(isa<TemplateSpecializationType>(Param) &&
1433 "injected class name is not a template specialization type");
1434 // fall through
1435 }
1436
Douglas Gregor705c9002009-06-26 20:57:09 +00001437 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001438 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001439 // TT<T>
1440 // TT<i>
1441 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001442 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001443 const TemplateSpecializationType *SpecParam =
1444 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001445
Richard Smith9b296e32016-04-25 19:09:05 +00001446 // When Arg cannot be a derived class, we can just try to deduce template
1447 // arguments from the template-id.
1448 const RecordType *RecordT = Arg->getAs<RecordType>();
1449 if (!(TDF & TDF_DerivedClass) || !RecordT)
1450 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1451 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Richard Smith9b296e32016-04-25 19:09:05 +00001453 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001455
Richard Smith9b296e32016-04-25 19:09:05 +00001456 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1457 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Richard Smith9b296e32016-04-25 19:09:05 +00001459 if (Result == Sema::TDK_Success)
1460 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001461
Richard Smith9b296e32016-04-25 19:09:05 +00001462 // We cannot inspect base classes as part of deduction when the type
1463 // is incomplete, so either instantiate any templates necessary to
1464 // complete the type, or skip over it if it cannot be completed.
1465 if (!S.isCompleteType(Info.getLocation(), Arg))
1466 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001467
Richard Smith9b296e32016-04-25 19:09:05 +00001468 // C++14 [temp.deduct.call] p4b3:
1469 // If P is a class and P has the form simple-template-id, then the
1470 // transformed A can be a derived class of the deduced A. Likewise if
1471 // P is a pointer to a class of the form simple-template-id, the
1472 // transformed A can be a pointer to a derived class pointed to by the
1473 // deduced A.
1474 //
1475 // These alternatives are considered only if type deduction would
1476 // otherwise fail. If they yield more than one possible deduced A, the
1477 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001478
Faisal Vali683b0742016-05-19 02:28:21 +00001479 // Reset the incorrectly deduced argument from above.
1480 Deduced = DeducedOrig;
1481
1482 // Use data recursion to crawl through the list of base classes.
1483 // Visited contains the set of nodes we have already visited, while
1484 // ToVisit is our stack of records that we still need to visit.
1485 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1486 SmallVector<const RecordType *, 8> ToVisit;
1487 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001488 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001489 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001490 while (!ToVisit.empty()) {
1491 // Retrieve the next class in the inheritance hierarchy.
1492 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001493
Faisal Vali683b0742016-05-19 02:28:21 +00001494 // If we have already seen this type, skip it.
1495 if (!Visited.insert(NextT).second)
1496 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001497
Faisal Vali683b0742016-05-19 02:28:21 +00001498 // If this is a base class, try to perform template argument
1499 // deduction from it.
1500 if (NextT != RecordT) {
1501 TemplateDeductionInfo BaseInfo(Info.getLocation());
1502 Sema::TemplateDeductionResult BaseResult =
1503 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1504 QualType(NextT, 0), BaseInfo, Deduced);
1505
1506 // If template argument deduction for this base was successful,
1507 // note that we had some success. Otherwise, ignore any deductions
1508 // from this base class.
1509 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001510 // If we've already seen some success, then deduction fails due to
1511 // an ambiguity (temp.deduct.call p5).
1512 if (Successful)
1513 return Sema::TDK_MiscellaneousDeductionFailure;
1514
Faisal Vali683b0742016-05-19 02:28:21 +00001515 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001516 std::swap(SuccessfulDeduced, Deduced);
1517
Faisal Vali683b0742016-05-19 02:28:21 +00001518 Info.Param = BaseInfo.Param;
1519 Info.FirstArg = BaseInfo.FirstArg;
1520 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001521 }
1522
1523 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001524 }
Mike Stump11289f42009-09-09 15:08:12 +00001525
Faisal Vali683b0742016-05-19 02:28:21 +00001526 // Visit base classes
1527 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1528 for (const auto &Base : Next->bases()) {
1529 assert(Base.getType()->isRecordType() &&
1530 "Base class that isn't a record?");
1531 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1532 }
1533 }
Mike Stump11289f42009-09-09 15:08:12 +00001534
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001535 if (Successful) {
1536 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001537 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001538 }
Richard Smith9b296e32016-04-25 19:09:05 +00001539
Douglas Gregore81f3e72009-07-07 23:09:34 +00001540 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001541 }
1542
Douglas Gregor637d9982009-06-10 23:47:09 +00001543 // T type::*
1544 // T T::*
1545 // T (type::*)()
1546 // type (T::*)()
1547 // type (type::*)(T)
1548 // type (T::*)(T)
1549 // T (type::*)(T)
1550 // T (T::*)()
1551 // T (T::*)(T)
1552 case Type::MemberPointer: {
1553 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1554 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1555 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001556 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001557
David Majnemera381cda2015-11-30 20:34:28 +00001558 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1559 if (ParamPointeeType->isFunctionType())
1560 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1561 /*IsCtorOrDtor=*/false, Info.getLocation());
1562 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1563 if (ArgPointeeType->isFunctionType())
1564 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1565 /*IsCtorOrDtor=*/false, Info.getLocation());
1566
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001567 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001568 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001569 ParamPointeeType,
1570 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001571 Info, Deduced,
1572 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001573 return Result;
1574
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001575 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1576 QualType(MemPtrParam->getClass(), 0),
1577 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001578 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001579 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001580 }
1581
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001582 // (clang extension)
1583 //
Mike Stump11289f42009-09-09 15:08:12 +00001584 // type(^)(T)
1585 // T(^)()
1586 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001587 case Type::BlockPointer: {
1588 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1589 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Anders Carlssona767eee2009-06-12 16:23:10 +00001591 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001592 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001593
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001594 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1595 BlockPtrParam->getPointeeType(),
1596 BlockPtrArg->getPointeeType(),
1597 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001598 }
1599
Douglas Gregor39c02722011-06-15 16:02:29 +00001600 // (clang extension)
1601 //
1602 // T __attribute__(((ext_vector_type(<integral constant>))))
1603 case Type::ExtVector: {
1604 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1605 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1606 // Make sure that the vectors have the same number of elements.
1607 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1608 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001609
Douglas Gregor39c02722011-06-15 16:02:29 +00001610 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001611 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1612 VectorParam->getElementType(),
1613 VectorArg->getElementType(),
1614 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001615 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001616
1617 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001618 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1619 // We can't check the number of elements, since the argument has a
1620 // dependent number of elements. This can only occur during partial
1621 // ordering.
1622
1623 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001624 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1625 VectorParam->getElementType(),
1626 VectorArg->getElementType(),
1627 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001628 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001629
Douglas Gregor39c02722011-06-15 16:02:29 +00001630 return Sema::TDK_NonDeducedMismatch;
1631 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001632
Douglas Gregor39c02722011-06-15 16:02:29 +00001633 // (clang extension)
1634 //
1635 // T __attribute__(((ext_vector_type(N))))
1636 case Type::DependentSizedExtVector: {
1637 const DependentSizedExtVectorType *VectorParam
1638 = cast<DependentSizedExtVectorType>(Param);
1639
1640 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1641 // Perform deduction on the element types.
1642 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001643 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1644 VectorParam->getElementType(),
1645 VectorArg->getElementType(),
1646 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001647 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001648
Douglas Gregor39c02722011-06-15 16:02:29 +00001649 // Perform deduction on the vector size, if we can.
1650 NonTypeTemplateParmDecl *NTTP
1651 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1652 if (!NTTP)
1653 return Sema::TDK_Success;
1654
1655 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1656 ArgSize = VectorArg->getNumElements();
1657 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1658 false, Info, Deduced);
1659 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001660
1661 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001662 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1663 // Perform deduction on the element types.
1664 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001665 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1666 VectorParam->getElementType(),
1667 VectorArg->getElementType(),
1668 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001669 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001670
Douglas Gregor39c02722011-06-15 16:02:29 +00001671 // Perform deduction on the vector size, if we can.
1672 NonTypeTemplateParmDecl *NTTP
1673 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1674 if (!NTTP)
1675 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001676
Douglas Gregor39c02722011-06-15 16:02:29 +00001677 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1678 Info, Deduced);
1679 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001680
Douglas Gregor39c02722011-06-15 16:02:29 +00001681 return Sema::TDK_NonDeducedMismatch;
1682 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001683
Douglas Gregor637d9982009-06-10 23:47:09 +00001684 case Type::TypeOfExpr:
1685 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001686 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001687 case Type::UnresolvedUsing:
1688 case Type::Decltype:
1689 case Type::UnaryTransform:
1690 case Type::Auto:
1691 case Type::DependentTemplateSpecialization:
1692 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001693 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001694 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001695 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001696 }
1697
David Blaikiee4d798f2012-01-20 21:50:17 +00001698 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001699}
1700
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001701static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001702DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001703 TemplateParameterList *TemplateParams,
1704 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001705 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001706 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001707 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001708 // If the template argument is a pack expansion, perform template argument
1709 // deduction against the pattern of that expansion. This only occurs during
1710 // partial ordering.
1711 if (Arg.isPackExpansion())
1712 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001714 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001715 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001716 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001717
1718 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001719 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001720 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1721 Param.getAsType(),
1722 Arg.getAsType(),
1723 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001724 Info.FirstArg = Param;
1725 Info.SecondArg = Arg;
1726 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001727
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001728 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001729 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001731 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001732 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001733 Info.FirstArg = Param;
1734 Info.SecondArg = Arg;
1735 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001736
1737 case TemplateArgument::TemplateExpansion:
1738 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001740 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001741 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001742 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001743 return Sema::TDK_Success;
1744
1745 Info.FirstArg = Param;
1746 Info.SecondArg = Arg;
1747 return Sema::TDK_NonDeducedMismatch;
1748
1749 case TemplateArgument::NullPtr:
1750 if (Arg.getKind() == TemplateArgument::NullPtr &&
1751 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001752 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001754 Info.FirstArg = Param;
1755 Info.SecondArg = Arg;
1756 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001758 case TemplateArgument::Integral:
1759 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001760 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001761 return Sema::TDK_Success;
1762
1763 Info.FirstArg = Param;
1764 Info.SecondArg = Arg;
1765 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001766 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001767
1768 if (Arg.getKind() == TemplateArgument::Expression) {
1769 Info.FirstArg = Param;
1770 Info.SecondArg = Arg;
1771 return Sema::TDK_NonDeducedMismatch;
1772 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001773
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001774 Info.FirstArg = Param;
1775 Info.SecondArg = Arg;
1776 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001777
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001778 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001779 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001780 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1781 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001782 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001783 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001784 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001785 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001786 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001787 if (Arg.getKind() == TemplateArgument::NullPtr)
1788 return DeduceNullPtrTemplateArgument(S, NTTP, Arg.getNullPtrType(),
1789 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001790 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001791 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001792 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001793 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001794 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001795 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001797 Info.FirstArg = Param;
1798 Info.SecondArg = Arg;
1799 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001802 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001803 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001804 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001805 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001806 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001807 }
Mike Stump11289f42009-09-09 15:08:12 +00001808
David Blaikiee4d798f2012-01-20 21:50:17 +00001809 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001810}
1811
Douglas Gregor7baabef2010-12-22 18:17:10 +00001812/// \brief Determine whether there is a template argument to be used for
1813/// deduction.
1814///
1815/// This routine "expands" argument packs in-place, overriding its input
1816/// parameters so that \c Args[ArgIdx] will be the available template argument.
1817///
1818/// \returns true if there is another template argument (which will be at
1819/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001821 unsigned &ArgIdx,
1822 unsigned &NumArgs) {
1823 if (ArgIdx == NumArgs)
1824 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001825
Douglas Gregor7baabef2010-12-22 18:17:10 +00001826 const TemplateArgument &Arg = Args[ArgIdx];
1827 if (Arg.getKind() != TemplateArgument::Pack)
1828 return true;
1829
1830 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1831 Args = Arg.pack_begin();
1832 NumArgs = Arg.pack_size();
1833 ArgIdx = 0;
1834 return ArgIdx < NumArgs;
1835}
1836
Douglas Gregord0ad2942010-12-23 01:24:45 +00001837/// \brief Determine whether the given set of template arguments has a pack
1838/// expansion that is not the last template argument.
1839static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1840 unsigned NumArgs) {
1841 unsigned ArgIdx = 0;
1842 while (ArgIdx < NumArgs) {
1843 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Douglas Gregord0ad2942010-12-23 01:24:45 +00001845 // Unwrap argument packs.
1846 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1847 Args = Arg.pack_begin();
1848 NumArgs = Arg.pack_size();
1849 ArgIdx = 0;
1850 continue;
1851 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001852
Douglas Gregord0ad2942010-12-23 01:24:45 +00001853 ++ArgIdx;
1854 if (ArgIdx == NumArgs)
1855 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Douglas Gregord0ad2942010-12-23 01:24:45 +00001857 if (Arg.isPackExpansion())
1858 return true;
1859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860
Douglas Gregord0ad2942010-12-23 01:24:45 +00001861 return false;
1862}
1863
Douglas Gregor7baabef2010-12-22 18:17:10 +00001864static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001865DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001866 const TemplateArgument *Params, unsigned NumParams,
1867 const TemplateArgument *Args, unsigned NumArgs,
1868 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001869 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1870 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001871 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872 // If the template argument list of P contains a pack expansion that is not
1873 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001874 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001875 if (hasPackExpansionBeforeEnd(Params, NumParams))
1876 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001877
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001878 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879 // If P has a form that contains <T> or <i>, then each argument Pi of the
1880 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001881 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001882 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001884 ++ParamIdx) {
1885 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001886 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Douglas Gregor7baabef2010-12-22 18:17:10 +00001888 // Check whether we have enough arguments.
1889 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001890 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1891 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001893 if (Args[ArgIdx].isPackExpansion()) {
1894 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1895 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001896 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001899 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001900 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001901 = DeduceTemplateArguments(S, TemplateParams,
1902 Params[ParamIdx], Args[ArgIdx],
1903 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904 return Result;
1905
Douglas Gregor7baabef2010-12-22 18:17:10 +00001906 // Move to the next argument.
1907 ++ArgIdx;
1908 continue;
1909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001910
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001911 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // If Pi is a pack expansion, then the pattern of Pi is compared with
1915 // each remaining argument in the template argument list of A. Each
1916 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001917 // template parameter packs expanded by Pi.
1918 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 // FIXME: If there are no remaining arguments, we can bail out early
1921 // and set any deduced parameter packs to an empty argument pack.
1922 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Richard Smith0a80d572014-05-29 01:12:14 +00001924 // Prepare to deduce the packs within the pattern.
1925 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001926
1927 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001929 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001930 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001931 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001932 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001936 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1937 Info, Deduced))
1938 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Richard Smith0a80d572014-05-29 01:12:14 +00001940 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001942
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001943 // Build argument packs for each of the parameter packs expanded by this
1944 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001945 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
Douglas Gregor7baabef2010-12-22 18:17:10 +00001949 return Sema::TDK_Success;
1950}
1951
Mike Stump11289f42009-09-09 15:08:12 +00001952static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001953DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001954 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001955 const TemplateArgumentList &ParamList,
1956 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001957 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001958 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001960 ParamList.data(), ParamList.size(),
1961 ArgList.data(), ArgList.size(),
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001962 Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001963}
1964
Douglas Gregor705c9002009-06-26 20:57:09 +00001965/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001966static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001967 const TemplateArgument &X,
1968 const TemplateArgument &Y) {
1969 if (X.getKind() != Y.getKind())
1970 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001971
Douglas Gregor705c9002009-06-26 20:57:09 +00001972 switch (X.getKind()) {
1973 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001974 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001975
Douglas Gregor705c9002009-06-26 20:57:09 +00001976 case TemplateArgument::Type:
1977 return Context.getCanonicalType(X.getAsType()) ==
1978 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor705c9002009-06-26 20:57:09 +00001980 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001981 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001982
1983 case TemplateArgument::NullPtr:
1984 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001985
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001986 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001987 case TemplateArgument::TemplateExpansion:
1988 return Context.getCanonicalTemplateName(
1989 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1990 Context.getCanonicalTemplateName(
1991 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Douglas Gregor705c9002009-06-26 20:57:09 +00001993 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001994 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001996 case TemplateArgument::Expression: {
1997 llvm::FoldingSetNodeID XID, YID;
1998 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002000 return XID == YID;
2001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor705c9002009-06-26 20:57:09 +00002003 case TemplateArgument::Pack:
2004 if (X.pack_size() != Y.pack_size())
2005 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002006
2007 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2008 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002009 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002010 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002011 if (!isSameTemplateArg(Context, *XP, *YP))
2012 return false;
2013
2014 return true;
2015 }
2016
David Blaikiee4d798f2012-01-20 21:50:17 +00002017 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002018}
2019
Douglas Gregorca4686d2011-01-04 23:35:54 +00002020/// \brief Allocate a TemplateArgumentLoc where all locations have
2021/// been initialized to the given location.
2022///
James Dennett634962f2012-06-14 21:40:34 +00002023/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002024/// location information for.
2025///
2026/// \param NTTPType For a declaration template argument, the type of
2027/// the non-type template parameter that corresponds to this template
2028/// argument.
2029///
2030/// \param Loc The source location to use for the resulting template
2031/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002032TemplateArgumentLoc
2033Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2034 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002035 switch (Arg.getKind()) {
2036 case TemplateArgument::Null:
2037 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregorca4686d2011-01-04 23:35:54 +00002039 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002040 return TemplateArgumentLoc(
2041 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregorca4686d2011-01-04 23:35:54 +00002043 case TemplateArgument::Declaration: {
Richard Smith7873de02016-08-11 22:25:46 +00002044 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2045 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002046 return TemplateArgumentLoc(TemplateArgument(E), E);
2047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048
Eli Friedmanb826a002012-09-26 02:36:12 +00002049 case TemplateArgument::NullPtr: {
Richard Smith7873de02016-08-11 22:25:46 +00002050 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2051 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002052 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2053 E);
2054 }
2055
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002057 Expr *E =
2058 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002059 return TemplateArgumentLoc(TemplateArgument(E), E);
2060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002061
Douglas Gregor9d802122011-03-02 17:09:35 +00002062 case TemplateArgument::Template:
2063 case TemplateArgument::TemplateExpansion: {
2064 NestedNameSpecifierLocBuilder Builder;
2065 TemplateName Template = Arg.getAsTemplate();
2066 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002067 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002068 else if (QualifiedTemplateName *QTN =
2069 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002070 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002071
Douglas Gregor9d802122011-03-02 17:09:35 +00002072 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002073 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002074 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002075
2076 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002077 Loc, Loc);
2078 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002079
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080 case TemplateArgument::Expression:
2081 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregorca4686d2011-01-04 23:35:54 +00002083 case TemplateArgument::Pack:
2084 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
David Blaikiee4d798f2012-01-20 21:50:17 +00002087 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002088}
2089
2090
2091/// \brief Convert the given deduced template argument and add it to the set of
2092/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002093static bool
2094ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2095 DeducedTemplateArgument Arg,
2096 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002097 TemplateDeductionInfo &Info,
2098 bool InFunctionTemplate,
2099 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002100 // First, for a non-type template parameter type that is
2101 // initialized by a declaration, we need the type of the
2102 // corresponding non-type template parameter.
2103 QualType NTTPType;
2104 if (NonTypeTemplateParmDecl *NTTP =
2105 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2106 NTTPType = NTTP->getType();
2107 if (NTTPType->isDependentType()) {
David Majnemer8b622692016-07-03 21:17:51 +00002108 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith37acb792016-02-03 20:15:01 +00002109 NTTPType = S.SubstType(NTTPType,
2110 MultiLevelTemplateArgumentList(TemplateArgs),
2111 NTTP->getLocation(),
2112 NTTP->getDeclName());
2113 if (NTTPType.isNull())
2114 return true;
2115 }
2116 }
2117
2118 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2119 unsigned ArgumentPackIndex) {
2120 // Convert the deduced template argument into a template
2121 // argument that we can check, almost as if the user had written
2122 // the template argument explicitly.
2123 TemplateArgumentLoc ArgLoc =
Richard Smith7873de02016-08-11 22:25:46 +00002124 S.getTrivialTemplateArgumentLoc(Arg, NTTPType, Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002125
2126 // Check the template argument, converting it as necessary.
2127 return S.CheckTemplateArgument(
2128 Param, ArgLoc, Template, Template->getLocation(),
2129 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2130 InFunctionTemplate
2131 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2132 : Sema::CTAK_Deduced)
2133 : Sema::CTAK_Specified);
2134 };
2135
Douglas Gregorca4686d2011-01-04 23:35:54 +00002136 if (Arg.getKind() == TemplateArgument::Pack) {
2137 // This is a template argument pack, so check each of its arguments against
2138 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002139 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002140 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002141 // When converting the deduced template argument, append it to the
2142 // general output list. We need to do this so that the template argument
2143 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002144 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002145 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002146 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2147 "deduced nested pack");
2148 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150
Douglas Gregor51bc5712011-01-05 20:52:18 +00002151 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002152 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Richard Smithdf18ee92016-02-03 20:40:30 +00002155 // If the pack is empty, we still need to substitute into the parameter
2156 // itself, in case that substitution fails. For non-type parameters, we did
2157 // this above. For type parameters, no substitution is ever required.
2158 auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2159 if (TTP && PackedArgsBuilder.empty()) {
2160 // Set up a template instantiation context.
2161 LocalInstantiationScope Scope(S);
2162 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2163 TTP, Output,
2164 Template->getSourceRange());
2165 if (Inst.isInvalid())
2166 return true;
2167
David Majnemer8b622692016-07-03 21:17:51 +00002168 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smithdf18ee92016-02-03 20:40:30 +00002169 if (!S.SubstDecl(TTP, S.CurContext,
2170 MultiLevelTemplateArgumentList(TemplateArgs)))
2171 return true;
2172 }
Richard Smith37acb792016-02-03 20:15:01 +00002173
Douglas Gregorca4686d2011-01-04 23:35:54 +00002174 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002175 Output.push_back(
2176 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177 return false;
2178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
Richard Smith37acb792016-02-03 20:15:01 +00002180 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002181}
2182
Douglas Gregor684268d2010-04-29 06:21:43 +00002183/// Complete template argument deduction for a class template partial
2184/// specialization.
2185static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002187 ClassTemplatePartialSpecializationDecl *Partial,
2188 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002189 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002190 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002191 // Unevaluated SFINAE context.
2192 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002193 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194
Douglas Gregor684268d2010-04-29 06:21:43 +00002195 Sema::ContextRAII SavedContext(S, Partial);
2196
2197 // C++ [temp.deduct.type]p2:
2198 // [...] or if any template argument remains neither deduced nor
2199 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002200 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002201 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2202 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002203 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002204 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002205 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002206 return Sema::TDK_Incomplete;
2207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208
Douglas Gregorca4686d2011-01-04 23:35:54 +00002209 // We have deduced this argument, so it still needs to be
2210 // checked and converted.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002211 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002212 Partial, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002213 Builder)) {
2214 Info.Param = makeTemplateParameter(Param);
2215 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002216 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002217 return Sema::TDK_SubstitutionFailure;
2218 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220
Douglas Gregor684268d2010-04-29 06:21:43 +00002221 // Form the template argument list from the deduced template arguments.
2222 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002223 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002224
Douglas Gregor684268d2010-04-29 06:21:43 +00002225 Info.reset(DeducedArgumentList);
2226
2227 // Substitute the deduced template arguments into the template
2228 // arguments of the class template partial specialization, and
2229 // verify that the instantiated template arguments are both valid
2230 // and are equivalent to the template arguments originally provided
2231 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002232 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002233 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002234 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002235 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002236 const TemplateArgumentLoc *PartialTemplateArgs
2237 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002238
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002239 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2240 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002241
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002242 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002243 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2244 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2245 if (ParamIdx >= Partial->getTemplateParameters()->size())
2246 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2247
2248 Decl *Param
2249 = const_cast<NamedDecl *>(
2250 Partial->getTemplateParameters()->getParam(ParamIdx));
2251 Info.Param = makeTemplateParameter(Param);
2252 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2253 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002254 }
2255
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002256 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002257 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002258 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002259 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260
Douglas Gregorca4686d2011-01-04 23:35:54 +00002261 TemplateParameterList *TemplateParams
2262 = ClassTemplate->getTemplateParameters();
2263 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002264 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002265 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002266 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002267 Info.FirstArg = TemplateArgs[I];
2268 Info.SecondArg = InstArg;
2269 return Sema::TDK_NonDeducedMismatch;
2270 }
2271 }
2272
2273 if (Trap.hasErrorOccurred())
2274 return Sema::TDK_SubstitutionFailure;
2275
2276 return Sema::TDK_Success;
2277}
2278
Douglas Gregor170bc422009-06-12 22:31:52 +00002279/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002280/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002281/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002282Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002283Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002284 const TemplateArgumentList &TemplateArgs,
2285 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002286 if (Partial->isInvalidDecl())
2287 return TDK_Invalid;
2288
Douglas Gregor170bc422009-06-12 22:31:52 +00002289 // C++ [temp.class.spec.match]p2:
2290 // A partial specialization matches a given actual template
2291 // argument list if the template arguments of the partial
2292 // specialization can be deduced from the actual template argument
2293 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002294
2295 // Unevaluated SFINAE context.
2296 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002297 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002298
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002299 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002300 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002301 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002302 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002303 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002304 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002305 TemplateArgs, Info, Deduced))
2306 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002307
Richard Smith80934652012-07-16 01:09:10 +00002308 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002309 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2310 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002311 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002312 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002313
Douglas Gregore1416332009-06-14 08:02:22 +00002314 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002315 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002316
2317 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002318 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002319}
Douglas Gregor91772d12009-06-13 00:26:55 +00002320
Larisse Voufo39a1e502013-08-06 01:03:05 +00002321/// Complete template argument deduction for a variable template partial
2322/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002323/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2324/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2325/// VarTemplate(Partial)SpecializationDecl with a new data
2326/// structure Template(Partial)SpecializationDecl, and
2327/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002328static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2329 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2330 const TemplateArgumentList &TemplateArgs,
2331 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2332 TemplateDeductionInfo &Info) {
2333 // Unevaluated SFINAE context.
2334 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2335 Sema::SFINAETrap Trap(S);
2336
2337 // C++ [temp.deduct.type]p2:
2338 // [...] or if any template argument remains neither deduced nor
2339 // explicitly specified, template argument deduction fails.
2340 SmallVector<TemplateArgument, 4> Builder;
2341 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2342 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2343 NamedDecl *Param = PartialParams->getParam(I);
2344 if (Deduced[I].isNull()) {
2345 Info.Param = makeTemplateParameter(Param);
2346 return Sema::TDK_Incomplete;
2347 }
2348
2349 // We have deduced this argument, so it still needs to be
2350 // checked and converted.
Richard Smith37acb792016-02-03 20:15:01 +00002351 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2352 Info, false, Builder)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002353 Info.Param = makeTemplateParameter(Param);
2354 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002355 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002356 return Sema::TDK_SubstitutionFailure;
2357 }
2358 }
2359
2360 // Form the template argument list from the deduced template arguments.
2361 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
David Majnemer8b622692016-07-03 21:17:51 +00002362 S.Context, Builder);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002363
2364 Info.reset(DeducedArgumentList);
2365
2366 // Substitute the deduced template arguments into the template
2367 // arguments of the class template partial specialization, and
2368 // verify that the instantiated template arguments are both valid
2369 // and are equivalent to the template arguments originally provided
2370 // to the class template.
2371 LocalInstantiationScope InstScope(S);
2372 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002373 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2374 = Partial->getTemplateArgsAsWritten();
2375 const TemplateArgumentLoc *PartialTemplateArgs
2376 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002377
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002378 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2379 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002380
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002381 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002382 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2383 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2384 if (ParamIdx >= Partial->getTemplateParameters()->size())
2385 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2386
2387 Decl *Param = const_cast<NamedDecl *>(
2388 Partial->getTemplateParameters()->getParam(ParamIdx));
2389 Info.Param = makeTemplateParameter(Param);
2390 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2391 return Sema::TDK_SubstitutionFailure;
2392 }
2393 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2394 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2395 false, ConvertedInstArgs))
2396 return Sema::TDK_SubstitutionFailure;
2397
2398 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2399 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2400 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2401 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2402 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2403 Info.FirstArg = TemplateArgs[I];
2404 Info.SecondArg = InstArg;
2405 return Sema::TDK_NonDeducedMismatch;
2406 }
2407 }
2408
2409 if (Trap.hasErrorOccurred())
2410 return Sema::TDK_SubstitutionFailure;
2411
2412 return Sema::TDK_Success;
2413}
2414
2415/// \brief Perform template argument deduction to determine whether
2416/// the given template arguments match the given variable template
2417/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002418/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2419/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2420/// VarTemplate(Partial)SpecializationDecl with a new data
2421/// structure Template(Partial)SpecializationDecl, and
2422/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002423Sema::TemplateDeductionResult
2424Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2425 const TemplateArgumentList &TemplateArgs,
2426 TemplateDeductionInfo &Info) {
2427 if (Partial->isInvalidDecl())
2428 return TDK_Invalid;
2429
2430 // C++ [temp.class.spec.match]p2:
2431 // A partial specialization matches a given actual template
2432 // argument list if the template arguments of the partial
2433 // specialization can be deduced from the actual template argument
2434 // list (14.8.2).
2435
2436 // Unevaluated SFINAE context.
2437 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2438 SFINAETrap Trap(*this);
2439
2440 SmallVector<DeducedTemplateArgument, 4> Deduced;
2441 Deduced.resize(Partial->getTemplateParameters()->size());
2442 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2443 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2444 TemplateArgs, Info, Deduced))
2445 return Result;
2446
2447 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002448 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2449 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002450 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002451 return TDK_InstantiationDepth;
2452
2453 if (Trap.hasErrorOccurred())
2454 return Sema::TDK_SubstitutionFailure;
2455
2456 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2457 Deduced, Info);
2458}
2459
Douglas Gregorfc516c92009-06-26 23:27:24 +00002460/// \brief Determine whether the given type T is a simple-template-id type.
2461static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002462 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002463 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002464 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002465
Douglas Gregorfc516c92009-06-26 23:27:24 +00002466 return false;
2467}
Douglas Gregor9b146582009-07-08 20:55:45 +00002468
2469/// \brief Substitute the explicitly-provided template arguments into the
2470/// given function template according to C++ [temp.arg.explicit].
2471///
2472/// \param FunctionTemplate the function template into which the explicit
2473/// template arguments will be substituted.
2474///
James Dennett634962f2012-06-14 21:40:34 +00002475/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002476/// arguments.
2477///
Mike Stump11289f42009-09-09 15:08:12 +00002478/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002479/// with the converted and checked explicit template arguments.
2480///
Mike Stump11289f42009-09-09 15:08:12 +00002481/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002482/// parameters.
2483///
2484/// \param FunctionType if non-NULL, the result type of the function template
2485/// will also be instantiated and the pointed-to value will be updated with
2486/// the instantiated function type.
2487///
2488/// \param Info if substitution fails for any reason, this object will be
2489/// populated with more information about the failure.
2490///
2491/// \returns TDK_Success if substitution was successful, or some failure
2492/// condition.
2493Sema::TemplateDeductionResult
2494Sema::SubstituteExplicitTemplateArguments(
2495 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002496 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002497 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2498 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002499 QualType *FunctionType,
2500 TemplateDeductionInfo &Info) {
2501 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2502 TemplateParameterList *TemplateParams
2503 = FunctionTemplate->getTemplateParameters();
2504
John McCall6b51f282009-11-23 01:53:49 +00002505 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002506 // No arguments to substitute; just copy over the parameter types and
2507 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002508 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002509 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002510
Douglas Gregor9b146582009-07-08 20:55:45 +00002511 if (FunctionType)
2512 *FunctionType = Function->getType();
2513 return TDK_Success;
2514 }
Mike Stump11289f42009-09-09 15:08:12 +00002515
Eli Friedman77dcc722012-02-08 03:07:05 +00002516 // Unevaluated SFINAE context.
2517 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002518 SFINAETrap Trap(*this);
2519
Douglas Gregor9b146582009-07-08 20:55:45 +00002520 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002521 // Template arguments that are present shall be specified in the
2522 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002523 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002524 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002525 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002526
2527 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002528 // explicitly-specified template arguments against this function template,
2529 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002530 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002531 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2532 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002533 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2534 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002535 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002536 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002537
Douglas Gregor9b146582009-07-08 20:55:45 +00002538 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002539 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002540 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002541 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002542 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002543 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002544 if (Index >= TemplateParams->size())
2545 Index = TemplateParams->size() - 1;
2546 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002547 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregor9b146582009-07-08 20:55:45 +00002550 // Form the template argument list from the explicitly-specified
2551 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002552 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002553 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002554 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555
John McCall036855a2010-10-12 19:40:14 +00002556 // Template argument deduction and the final substitution should be
2557 // done in the context of the templated declaration. Explicit
2558 // argument substitution, on the other hand, needs to happen in the
2559 // calling context.
2560 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2561
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002563 // note that the template argument pack is partially substituted and record
2564 // the explicit template arguments. They'll be used as part of deduction
2565 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002566 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2567 const TemplateArgument &Arg = Builder[I];
2568 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002569 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002571 Arg.pack_begin(),
2572 Arg.pack_size());
2573 break;
2574 }
2575 }
2576
Richard Smith5e580292012-02-10 09:58:53 +00002577 const FunctionProtoType *Proto
2578 = Function->getType()->getAs<FunctionProtoType>();
2579 assert(Proto && "Function template does not have a prototype?");
2580
Richard Smith70b13042015-01-09 01:19:56 +00002581 // Isolate our substituted parameters from our caller.
2582 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2583
John McCallc8e321d2016-03-01 02:09:25 +00002584 ExtParameterInfoBuilder ExtParamInfos;
2585
Douglas Gregor9b146582009-07-08 20:55:45 +00002586 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002587 // explicitly-specified template arguments. If the function has a trailing
2588 // return type, substitute it after the arguments to ensure we substitute
2589 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002590 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002591 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002592 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002593 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002594 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002595 return TDK_SubstitutionFailure;
2596 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002597
Richard Smith5e580292012-02-10 09:58:53 +00002598 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002599 QualType ResultType;
2600 {
2601 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002602 // If a declaration declares a member function or member function
2603 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002604 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002605 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002606 // declarator.
2607 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002608 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2610 ThisContext = Method->getParent();
2611 ThisTypeQuals = Method->getTypeQualifiers();
2612 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002613
Douglas Gregor3024f072012-04-16 07:05:22 +00002614 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002615 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002616
2617 ResultType =
2618 SubstType(Proto->getReturnType(),
2619 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2620 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002621 if (ResultType.isNull() || Trap.hasErrorOccurred())
2622 return TDK_SubstitutionFailure;
2623 }
John McCallc8e321d2016-03-01 02:09:25 +00002624
Richard Smith5e580292012-02-10 09:58:53 +00002625 // Instantiate the types of each of the function parameters given the
2626 // explicitly-specified template arguments if we didn't do so earlier.
2627 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002628 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002629 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002630 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002631 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002632 return TDK_SubstitutionFailure;
2633
Douglas Gregor9b146582009-07-08 20:55:45 +00002634 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002635 auto EPI = Proto->getExtProtoInfo();
2636 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002637 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002638 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002639 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002640 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002641 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2642 return TDK_SubstitutionFailure;
2643 }
Mike Stump11289f42009-09-09 15:08:12 +00002644
Douglas Gregor9b146582009-07-08 20:55:45 +00002645 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002646 // Trailing template arguments that can be deduced (14.8.2) may be
2647 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002648 // template arguments can be deduced, they may all be omitted; in this
2649 // case, the empty template argument list <> itself may also be omitted.
2650 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002651 // Take all of the explicitly-specified arguments and put them into
2652 // the set of deduced template arguments. Explicitly-specified
2653 // parameter packs, however, will be set to NULL since the deduction
2654 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002655 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002656 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2657 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2658 if (Arg.getKind() == TemplateArgument::Pack)
2659 Deduced.push_back(DeducedTemplateArgument());
2660 else
2661 Deduced.push_back(Arg);
2662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Douglas Gregor9b146582009-07-08 20:55:45 +00002664 return TDK_Success;
2665}
2666
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002667/// \brief Check whether the deduced argument type for a call to a function
2668/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002669static bool
2670CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002671 QualType DeducedA) {
2672 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002673
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002674 QualType A = OriginalArg.OriginalArgType;
2675 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002676
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002677 // Check for type equality (top-level cv-qualifiers are ignored).
2678 if (Context.hasSameUnqualifiedType(A, DeducedA))
2679 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002680
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002681 // Strip off references on the argument types; they aren't needed for
2682 // the following checks.
2683 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2684 DeducedA = DeducedARef->getPointeeType();
2685 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2686 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002687
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002688 // C++ [temp.deduct.call]p4:
2689 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002690 // - If the original P is a reference type, the deduced A (i.e., the
2691 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002692 // the transformed A.
2693 if (const ReferenceType *OriginalParamRef
2694 = OriginalParamType->getAs<ReferenceType>()) {
2695 // We don't want to keep the reference around any more.
2696 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002697
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002698 Qualifiers AQuals = A.getQualifiers();
2699 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002700
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002701 // Under Objective-C++ ARC, the deduced type may have implicitly
2702 // been given strong or (when dealing with a const reference)
2703 // unsafe_unretained lifetime. If so, update the original
2704 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002705 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002706 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2707 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2708 (DeducedAQuals.hasConst() &&
2709 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2710 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002711 }
2712
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002713 if (AQuals == DeducedAQuals) {
2714 // Qualifiers match; there's nothing to do.
2715 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002716 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002717 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002718 // Qualifiers are compatible, so have the argument type adopt the
2719 // deduced argument type's qualifiers as if we had performed the
2720 // qualification conversion.
2721 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2722 }
2723 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002724
2725 // - The transformed A can be another pointer or pointer to member
2726 // type that can be converted to the deduced A via a qualification
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002727 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002728 //
2729 // Also allow conversions which merely strip [[noreturn]] from function types
2730 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002731 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002732 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002733 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002734 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002735 (S.IsQualificationConversion(A, DeducedA, false,
2736 ObjCLifetimeConversion) ||
2737 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002738 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002739
2740
2741 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002742 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002743 // [...] Likewise, if P is a pointer to a class of the form
2744 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002745 // derived class pointed to by the deduced A.
2746 if (const PointerType *OriginalParamPtr
2747 = OriginalParamType->getAs<PointerType>()) {
2748 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2749 if (const PointerType *APtr = A->getAs<PointerType>()) {
2750 if (A->getPointeeType()->isRecordType()) {
2751 OriginalParamType = OriginalParamPtr->getPointeeType();
2752 DeducedA = DeducedAPtr->getPointeeType();
2753 A = APtr->getPointeeType();
2754 }
2755 }
2756 }
2757 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002758
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002759 if (Context.hasSameUnqualifiedType(A, DeducedA))
2760 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002761
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002762 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002763 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002764 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002765
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002766 return true;
2767}
2768
Mike Stump11289f42009-09-09 15:08:12 +00002769/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002770/// checking the deduced template arguments for completeness and forming
2771/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002772///
2773/// \param OriginalCallArgs If non-NULL, the original call arguments against
2774/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002775Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002776Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002777 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002778 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002779 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002780 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002781 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2782 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002783 TemplateParameterList *TemplateParams
2784 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002785
Eli Friedman77dcc722012-02-08 03:07:05 +00002786 // Unevaluated SFINAE context.
2787 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002788 SFINAETrap Trap(*this);
2789
Douglas Gregor9b146582009-07-08 20:55:45 +00002790 // Enter a new template instantiation context while we instantiate the
2791 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002792 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002793 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2794 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002795 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2796 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002797 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002798 return TDK_InstantiationDepth;
2799
John McCalle23b8712010-04-29 01:18:58 +00002800 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002801
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002802 // C++ [temp.deduct.type]p2:
2803 // [...] or if any template argument remains neither deduced nor
2804 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002805 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002806 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2807 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002808
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002809 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002810 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002811 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002813 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002814 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002815 // We may have had explicitly-specified template arguments for a
2816 // template parameter pack (that may or may not have been extended
2817 // via additional deduced arguments).
2818 if (Param->isParameterPack() && CurrentInstantiationScope) {
2819 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2820 Param) {
2821 // Forget the partially-substituted pack; its substitution is now
2822 // complete.
2823 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2824 }
2825 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002826 continue;
2827 }
Richard Smith37acb792016-02-03 20:15:01 +00002828
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002829 // We have deduced this argument, so it still needs to be
2830 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002831 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002832 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002833 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002834 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002835 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002836 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002837 return TDK_SubstitutionFailure;
2838 }
2839
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002840 continue;
2841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002843 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002845 // be deduced to an empty sequence of template arguments.
2846 // FIXME: Where did the word "trailing" come from?
2847 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002848 // We may have had explicitly-specified template arguments for this
2849 // template parameter pack. If so, our empty deduction extends the
2850 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2851 const TemplateArgument *ExplicitArgs;
2852 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002853 if (CurrentInstantiationScope &&
2854 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002855 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002856 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002857 Builder.push_back(TemplateArgument(
2858 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859
Richard Smithdf18ee92016-02-03 20:40:30 +00002860 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002861 // complete.
2862 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2863 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002864 // Go through the motions of checking the empty argument pack against
2865 // the parameter pack.
2866 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2867 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2868 FunctionTemplate, Info, true,
2869 Builder)) {
2870 Info.Param = makeTemplateParameter(Param);
2871 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002872 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Richard Smithdf18ee92016-02-03 20:40:30 +00002873 return TDK_SubstitutionFailure;
2874 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002875 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002876 continue;
2877 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002880 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002881 TemplateArgumentLoc DefArg
2882 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2883 FunctionTemplate->getLocation(),
2884 FunctionTemplate->getSourceRange().getEnd(),
2885 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002886 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002887
2888 // If there was no default argument, deduction is incomplete.
2889 if (DefArg.getArgument().isNull()) {
2890 Info.Param = makeTemplateParameter(
2891 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
David Majnemer8b622692016-07-03 21:17:51 +00002892 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002893 if (PartialOverloading) break;
2894
Richard Smithc87b9382013-07-04 01:01:24 +00002895 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002898 // Check whether we can actually use the default argument.
2899 if (CheckTemplateArgument(Param, DefArg,
2900 FunctionTemplate,
2901 FunctionTemplate->getLocation(),
2902 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002903 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002904 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002905 Info.Param = makeTemplateParameter(
2906 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002907 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002908 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002909 return TDK_SubstitutionFailure;
2910 }
2911
2912 // If we get here, we successfully used the default template argument.
2913 }
2914
2915 // Form the template argument list from the deduced template arguments.
2916 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002917 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002918 Info.reset(DeducedArgumentList);
2919
Mike Stump11289f42009-09-09 15:08:12 +00002920 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002921 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002922 DeclContext *Owner = FunctionTemplate->getDeclContext();
2923 if (FunctionTemplate->getFriendObjectKind())
2924 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002925 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002926 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002927 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002928 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002929 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002930
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002931 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002932 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933
Mike Stump11289f42009-09-09 15:08:12 +00002934 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002935 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002936 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2937 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002938 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002939
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002940 // There may have been an error that did not prevent us from constructing a
2941 // declaration. Mark the declaration invalid and return with a substitution
2942 // failure.
2943 if (Trap.hasErrorOccurred()) {
2944 Specialization->setInvalidDecl(true);
2945 return TDK_SubstitutionFailure;
2946 }
2947
Douglas Gregore65aacb2011-06-16 16:50:48 +00002948 if (OriginalCallArgs) {
2949 // C++ [temp.deduct.call]p4:
2950 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002951 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002952 // is transformed as described above). [...]
2953 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2954 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002955 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002956
Douglas Gregore65aacb2011-06-16 16:50:48 +00002957 if (ParamIdx >= Specialization->getNumParams())
2958 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002959
Douglas Gregore65aacb2011-06-16 16:50:48 +00002960 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002961 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2962 Info.FirstArg = TemplateArgument(DeducedA);
2963 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2964 Info.CallArgIndex = OriginalArg.ArgIdx;
2965 return TDK_DeducedMismatch;
2966 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002967 }
2968 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002969
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002970 // If we suppressed any diagnostics while performing template argument
2971 // deduction, and if we haven't already instantiated this declaration,
2972 // keep track of these diagnostics. They'll be emitted if this specialization
2973 // is actually used.
2974 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002975 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002976 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2977 if (Pos == SuppressedDiagnostics.end())
2978 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2979 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002981
Mike Stump11289f42009-09-09 15:08:12 +00002982 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002983}
2984
John McCall8d08b9b2010-08-27 09:08:28 +00002985/// Gets the type of a function for template-argument-deducton
2986/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002987static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002988 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002989 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002990 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002991 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002992 return QualType();
2993
John McCallc1f69982010-02-02 02:21:27 +00002994 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002995 if (Method->isInstance()) {
2996 // An instance method that's referenced in a form that doesn't
2997 // look like a member pointer is just invalid.
2998 if (!R.HasFormOfMemberPointer) return QualType();
2999
Richard Smith2a7d4812013-05-04 07:00:32 +00003000 return S.Context.getMemberPointerType(Fn->getType(),
3001 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003002 }
3003
3004 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003005 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003006}
3007
3008/// Apply the deduction rules for overload sets.
3009///
3010/// \return the null type if this argument should be treated as an
3011/// undeduced context
3012static QualType
3013ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003014 Expr *Arg, QualType ParamType,
3015 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016
John McCall8d08b9b2010-08-27 09:08:28 +00003017 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003018
John McCall8d08b9b2010-08-27 09:08:28 +00003019 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003020
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003021 // C++0x [temp.deduct.call]p4
3022 unsigned TDF = 0;
3023 if (ParamWasReference)
3024 TDF |= TDF_ParamWithReferenceType;
3025 if (R.IsAddressOfOperand)
3026 TDF |= TDF_IgnoreQualifiers;
3027
John McCallc1f69982010-02-02 02:21:27 +00003028 // C++0x [temp.deduct.call]p6:
3029 // When P is a function type, pointer to function type, or pointer
3030 // to member function type:
3031
3032 if (!ParamType->isFunctionType() &&
3033 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003034 !ParamType->isMemberFunctionPointerType()) {
3035 if (Ovl->hasExplicitTemplateArgs()) {
3036 // But we can still look for an explicit specialization.
3037 if (FunctionDecl *ExplicitSpec
3038 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003039 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003040 }
John McCallc1f69982010-02-02 02:21:27 +00003041
George Burgess IVcc2f3552016-03-19 21:51:45 +00003042 DeclAccessPair DAP;
3043 if (FunctionDecl *Viable =
3044 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3045 return GetTypeOfFunction(S, R, Viable);
3046
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003047 return QualType();
3048 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003049
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003050 // Gather the explicit template arguments, if any.
3051 TemplateArgumentListInfo ExplicitTemplateArgs;
3052 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003053 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003054 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003055 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3056 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003057 NamedDecl *D = (*I)->getUnderlyingDecl();
3058
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003059 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3060 // - If the argument is an overload set containing one or more
3061 // function templates, the parameter is treated as a
3062 // non-deduced context.
3063 if (!Ovl->hasExplicitTemplateArgs())
3064 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003065
3066 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003067 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003068 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003069 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3070 Specialization, Info))
3071 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003072
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003073 D = Specialization;
3074 }
John McCallc1f69982010-02-02 02:21:27 +00003075
3076 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003077 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003078 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003079
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003080 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003082 ArgType->isFunctionType())
3083 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084
John McCallc1f69982010-02-02 02:21:27 +00003085 // - If the argument is an overload set (not containing function
3086 // templates), trial argument deduction is attempted using each
3087 // of the members of the set. If deduction succeeds for only one
3088 // of the overload set members, that member is used as the
3089 // argument value for the deduction. If deduction succeeds for
3090 // more than one member of the overload set the parameter is
3091 // treated as a non-deduced context.
3092
3093 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3094 // Type deduction is done independently for each P/A pair, and
3095 // the deduced template argument values are then combined.
3096 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003097 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003098 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003099 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003100 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003101 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3102 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003103 if (Result) continue;
3104 if (!Match.isNull()) return QualType();
3105 Match = ArgType;
3106 }
3107
3108 return Match;
3109}
3110
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003112/// described in C++ [temp.deduct.call].
3113///
3114/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003115/// argument deduction based on this P/A pair because the argument is an
3116/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003117static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3118 TemplateParameterList *TemplateParams,
3119 QualType &ParamType,
3120 QualType &ArgType,
3121 Expr *Arg,
3122 unsigned &TDF) {
3123 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003124 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003126 if (ParamType.hasQualifiers())
3127 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003128
3129 // [...] If P is a reference type, the type referred to by P is
3130 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003131 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003132 if (ParamRefType)
3133 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003134
Nathan Sidwell96090022015-01-16 15:20:14 +00003135 // Overload sets usually make this parameter an undeduced context,
3136 // but there are sometimes special circumstances. Typically
3137 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003138 if (ArgType == S.Context.OverloadTy) {
3139 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3140 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003141 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003142 if (ArgType.isNull())
3143 return true;
3144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145
Douglas Gregor7825bf32011-01-06 22:09:01 +00003146 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003147 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003148 if (ArgType->isIncompleteArrayType()) {
3149 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003150 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003151 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003152
Douglas Gregor7825bf32011-01-06 22:09:01 +00003153 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003154 // If P is an rvalue reference to a cv-unqualified template
3155 // parameter and the argument is an lvalue, the type "lvalue
3156 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003157 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003158 !ParamType.getQualifiers() &&
3159 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 Arg->isLValue())
3161 ArgType = S.Context.getLValueReferenceType(ArgType);
3162 } else {
3163 // C++ [temp.deduct.call]p2:
3164 // If P is not a reference type:
3165 // - If A is an array type, the pointer type produced by the
3166 // array-to-pointer standard conversion (4.2) is used in place of
3167 // A for type deduction; otherwise,
3168 if (ArgType->isArrayType())
3169 ArgType = S.Context.getArrayDecayedType(ArgType);
3170 // - If A is a function type, the pointer type produced by the
3171 // function-to-pointer standard conversion (4.3) is used in place
3172 // of A for type deduction; otherwise,
3173 else if (ArgType->isFunctionType())
3174 ArgType = S.Context.getPointerType(ArgType);
3175 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003176 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003177 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003178 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003179 }
3180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181
Douglas Gregor7825bf32011-01-06 22:09:01 +00003182 // C++0x [temp.deduct.call]p4:
3183 // In general, the deduction process attempts to find template argument
3184 // values that will make the deduced A identical to A (after the type A
3185 // is transformed as described above). [...]
3186 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor7825bf32011-01-06 22:09:01 +00003188 // - If the original P is a reference type, the deduced A (i.e., the
3189 // type referred to by the reference) can be more cv-qualified than
3190 // the transformed A.
3191 if (ParamRefType)
3192 TDF |= TDF_ParamWithReferenceType;
3193 // - The transformed A can be another pointer or pointer to member
3194 // type that can be converted to the deduced A via a qualification
3195 // conversion (4.4).
3196 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3197 ArgType->isObjCObjectPointerType())
3198 TDF |= TDF_IgnoreQualifiers;
3199 // - If P is a class and P has the form simple-template-id, then the
3200 // transformed A can be a derived class of the deduced A. Likewise,
3201 // if P is a pointer to a class of the form simple-template-id, the
3202 // transformed A can be a pointer to a derived class pointed to by
3203 // the deduced A.
3204 if (isSimpleTemplateIdType(ParamType) ||
3205 (isa<PointerType>(ParamType) &&
3206 isSimpleTemplateIdType(
3207 ParamType->getAs<PointerType>()->getPointeeType())))
3208 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209
Douglas Gregor7825bf32011-01-06 22:09:01 +00003210 return false;
3211}
3212
Nico Weberc153d242014-07-28 00:02:09 +00003213static bool
3214hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3215 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003216
Hubert Tong3280b332015-06-25 00:25:49 +00003217static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3218 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3219 Expr *Arg, TemplateDeductionInfo &Info,
3220 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3221
3222/// \brief Attempt template argument deduction from an initializer list
3223/// deemed to be an argument in a function call.
3224static bool
3225DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3226 QualType AdjustedParamType, InitListExpr *ILE,
3227 TemplateDeductionInfo &Info,
3228 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3229 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003230
3231 // [temp.deduct.call] p1 (post CWG-1591)
3232 // If removing references and cv-qualifiers from P gives
3233 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3234 // non-empty initializer list (8.5.4), then deduction is performed instead for
3235 // each element of the initializer list, taking P0 as a function template
3236 // parameter type and the initializer element as its argument, and in the
3237 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3238 // length of the initializer list. Otherwise, an initializer list argument
3239 // causes the parameter to be considered a non-deduced context
3240
3241 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3242
3243 const bool IsDependentSizedArray =
3244 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3245
Faisal Validd76cc12015-12-10 12:29:11 +00003246 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003247
3248 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3249 S.isStdInitializerList(AdjustedParamType, &ElTy);
3250
3251 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003252 return false;
3253
3254 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003255 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3256 // deduce against the 'T' in T[N].
3257 if (ElTy.isNull()) {
3258 assert(!IsSTDList);
3259 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003260 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003261 // Deduction only needs to be done for dependent types.
3262 if (ElTy->isDependentType()) {
3263 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003264 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3265 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003266 return true;
3267 }
3268 }
3269 if (IsDependentSizedArray) {
3270 const DependentSizedArrayType *ArrTy =
3271 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3272 // Determine the array bound is something we can deduce.
3273 if (NonTypeTemplateParmDecl *NTTP =
3274 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3275 // We can perform template argument deduction for the given non-type
3276 // template parameter.
3277 assert(NTTP->getDepth() == 0 &&
3278 "Cannot deduce non-type template argument at depth > 0");
3279 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3280 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003281
Faisal Valif6dfdb32015-12-10 05:36:39 +00003282 Result = DeduceNonTypeTemplateArgument(
3283 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3284 /*ArrayBound=*/true, Info, Deduced);
3285 }
3286 }
Hubert Tong3280b332015-06-25 00:25:49 +00003287 return true;
3288}
3289
Sebastian Redl19181662012-03-15 21:40:51 +00003290/// \brief Perform template argument deduction by matching a parameter type
3291/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003292/// an initializer list that was originally matched against a parameter
3293/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003294static Sema::TemplateDeductionResult
3295DeduceTemplateArgumentByListElement(Sema &S,
3296 TemplateParameterList *TemplateParams,
3297 QualType ParamType, Expr *Arg,
3298 TemplateDeductionInfo &Info,
3299 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3300 unsigned TDF) {
3301 // Handle the case where an init list contains another init list as the
3302 // element.
3303 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003304 Sema::TemplateDeductionResult Result;
3305 if (!DeduceFromInitializerList(S, TemplateParams,
3306 ParamType.getNonReferenceType(), ILE, Info,
3307 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003308 return Sema::TDK_Success; // Just ignore this expression.
3309
Hubert Tong3280b332015-06-25 00:25:49 +00003310 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003311 }
3312
3313 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003314 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003315 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003316 ArgType, Arg, TDF)) {
3317 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003318 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003319 }
Sebastian Redl19181662012-03-15 21:40:51 +00003320 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003321 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003322}
3323
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003324/// \brief Perform template argument deduction from a function call
3325/// (C++ [temp.deduct.call]).
3326///
3327/// \param FunctionTemplate the function template for which we are performing
3328/// template argument deduction.
3329///
James Dennett18348b62012-06-22 08:52:37 +00003330/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003331/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003332///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003333/// \param Args the function call arguments
3334///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003335/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003336/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003337/// template argument deduction.
3338///
3339/// \param Info the argument will be updated to provide additional information
3340/// about template argument deduction.
3341///
3342/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003343Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3344 FunctionTemplateDecl *FunctionTemplate,
3345 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003346 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3347 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003348 if (FunctionTemplate->isInvalidDecl())
3349 return TDK_Invalid;
3350
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003351 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003352 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003353
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 // C++ [temp.deduct.call]p1:
3355 // Template argument deduction is done by comparing each function template
3356 // parameter type (call it P) with the type of the corresponding argument
3357 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003358 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003359 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003360 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003361 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003362 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003363 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003364 if (Proto->isTemplateVariadic())
3365 /* Do nothing */;
3366 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003367 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003370 }
Mike Stump11289f42009-09-09 15:08:12 +00003371
Douglas Gregor89026b52009-06-30 23:57:56 +00003372 // The types of the parameters from which we will perform template argument
3373 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003374 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003375 TemplateParameterList *TemplateParams
3376 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003377 SmallVector<DeducedTemplateArgument, 4> Deduced;
3378 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003379 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003380 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003381 TemplateDeductionResult Result =
3382 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003383 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003384 Deduced,
3385 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003386 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003387 Info);
3388 if (Result)
3389 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003390
3391 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003392 } else {
3393 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003394 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003395 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3396 }
Mike Stump11289f42009-09-09 15:08:12 +00003397
Douglas Gregor89026b52009-06-30 23:57:56 +00003398 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003399 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003400 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003401 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003402 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3403 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003404 QualType OrigParamType = ParamTypes[ParamIdx];
3405 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003406
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 = dyn_cast<PackExpansionType>(ParamType);
3409 if (!ParamExpansion) {
3410 // Simple case: matching a function parameter to a function argument.
3411 if (ArgIdx >= CheckArgs)
3412 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregor7825bf32011-01-06 22:09:01 +00003414 Expr *Arg = Args[ArgIdx++];
3415 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003416
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 unsigned TDF = 0;
3418 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3419 ParamType, ArgType, Arg,
3420 TDF))
3421 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
Douglas Gregor0c83c812011-10-09 22:06:46 +00003423 // If we have nothing to deduce, we're done.
3424 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3425 continue;
3426
Sebastian Redl43144e72012-01-17 22:49:58 +00003427 // If the argument is an initializer list ...
3428 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003429 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003430 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003431 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3432 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003433 continue;
3434
Hubert Tong3280b332015-06-25 00:25:49 +00003435 if (Result)
3436 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003437 // Don't track the argument type, since an initializer list has none.
3438 continue;
3439 }
3440
Douglas Gregore65aacb2011-06-16 16:50:48 +00003441 // Keep track of the argument type and corresponding parameter index,
3442 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003443 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003444 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003445
Douglas Gregor7825bf32011-01-06 22:09:01 +00003446 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003447 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3448 ParamType, ArgType,
3449 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003450 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003451
Douglas Gregor7825bf32011-01-06 22:09:01 +00003452 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Douglas Gregor7825bf32011-01-06 22:09:01 +00003455 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456 // For a function parameter pack that occurs at the end of the
3457 // parameter-declaration-list, the type A of each remaining argument of
3458 // the call is compared with the type P of the declarator-id of the
3459 // function parameter pack. Each comparison deduces template arguments
3460 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003461 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003463 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003464 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003465 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregor7825bf32011-01-06 22:09:01 +00003467 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003468 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3469 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470
Douglas Gregor7825bf32011-01-06 22:09:01 +00003471 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003472 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003473 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474
Douglas Gregore65aacb2011-06-16 16:50:48 +00003475 QualType OrigParamType = ParamPattern;
3476 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003477 Expr *Arg = Args[ArgIdx];
3478 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003479
Douglas Gregor7825bf32011-01-06 22:09:01 +00003480 unsigned TDF = 0;
3481 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3482 ParamType, ArgType, Arg,
3483 TDF)) {
3484 // We can't actually perform any deduction for this argument, so stop
3485 // deduction at this point.
3486 ++ArgIdx;
3487 break;
3488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Sebastian Redl43144e72012-01-17 22:49:58 +00003490 // As above, initializer lists need special handling.
3491 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003492 TemplateDeductionResult Result;
3493 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3494 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003495 ++ArgIdx;
3496 break;
3497 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003498
Hubert Tong3280b332015-06-25 00:25:49 +00003499 if (Result)
3500 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003501 } else {
3502
3503 // Keep track of the argument type and corresponding argument index,
3504 // so we can check for compatibility between the deduced A and A.
3505 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003506 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003507 ArgType));
3508
3509 if (TemplateDeductionResult Result
3510 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3511 ParamType, ArgType, Info,
3512 Deduced, TDF))
3513 return Result;
3514 }
Mike Stump11289f42009-09-09 15:08:12 +00003515
Richard Smith0a80d572014-05-29 01:12:14 +00003516 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregor7825bf32011-01-06 22:09:01 +00003519 // Build argument packs for each of the parameter packs expanded by this
3520 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003521 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor7825bf32011-01-06 22:09:01 +00003524 // After we've matching against a parameter pack, we're done.
3525 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003526 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003527
Mike Stump11289f42009-09-09 15:08:12 +00003528 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003529 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003530 Info, &OriginalCallArgs,
3531 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003532}
3533
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003534QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3535 QualType FunctionType) {
3536 if (ArgFunctionType.isNull())
3537 return ArgFunctionType;
3538
3539 const FunctionProtoType *FunctionTypeP =
3540 FunctionType->castAs<FunctionProtoType>();
3541 CallingConv CC = FunctionTypeP->getCallConv();
3542 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3543 const FunctionProtoType *ArgFunctionTypeP =
3544 ArgFunctionType->getAs<FunctionProtoType>();
3545 if (ArgFunctionTypeP->getCallConv() == CC &&
3546 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3547 return ArgFunctionType;
3548
3549 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3550 EI = EI.withNoReturn(NoReturn);
3551 ArgFunctionTypeP =
3552 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3553 return QualType(ArgFunctionTypeP, 0);
3554}
3555
Douglas Gregor9b146582009-07-08 20:55:45 +00003556/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003557/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3558/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003559///
3560/// \param FunctionTemplate the function template for which we are performing
3561/// template argument deduction.
3562///
James Dennett18348b62012-06-22 08:52:37 +00003563/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003564/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003565///
3566/// \param ArgFunctionType the function type that will be used as the
3567/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003568/// function template's function type. This type may be NULL, if there is no
3569/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003570///
3571/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003572/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003573/// template argument deduction.
3574///
3575/// \param Info the argument will be updated to provide additional information
3576/// about template argument deduction.
3577///
3578/// \returns the result of template argument deduction.
3579Sema::TemplateDeductionResult
3580Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003581 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003582 QualType ArgFunctionType,
3583 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003584 TemplateDeductionInfo &Info,
3585 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003586 if (FunctionTemplate->isInvalidDecl())
3587 return TDK_Invalid;
3588
Douglas Gregor9b146582009-07-08 20:55:45 +00003589 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3590 TemplateParameterList *TemplateParams
3591 = FunctionTemplate->getTemplateParameters();
3592 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003593 if (!InOverloadResolution)
3594 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Douglas Gregor9b146582009-07-08 20:55:45 +00003596 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003597 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003598 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003599 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003600 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003601 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003602 if (TemplateDeductionResult Result
3603 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003604 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003605 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003606 &FunctionType, Info))
3607 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003608
3609 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003610 }
3611
Eli Friedman77dcc722012-02-08 03:07:05 +00003612 // Unevaluated SFINAE context.
3613 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003614 SFINAETrap Trap(*this);
3615
John McCallc1f69982010-02-02 02:21:27 +00003616 Deduced.resize(TemplateParams->size());
3617
Richard Smith2a7d4812013-05-04 07:00:32 +00003618 // If the function has a deduced return type, substitute it for a dependent
3619 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003620 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003621 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003622 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003623 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003624 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003625 }
3626
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003627 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003628 unsigned TDF = TDF_TopLevelParameterTypeList;
3629 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003630 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003631 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003632 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003633 FunctionType, ArgFunctionType,
3634 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003635 return Result;
3636 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003639 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3640 NumExplicitlySpecified,
3641 Specialization, Info))
3642 return Result;
3643
Richard Smith2a7d4812013-05-04 07:00:32 +00003644 // If the function has a deduced return type, deduce it now, so we can check
3645 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003646 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003647 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003648 DeduceReturnType(Specialization, Info.getLocation(), false))
3649 return TDK_MiscellaneousDeductionFailure;
3650
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003651 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003652 // specialization with respect to arguments of compatible pointer to function
3653 // types, template argument deduction fails.
3654 if (!ArgFunctionType.isNull()) {
3655 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3656 Context.getCanonicalType(Specialization->getType()),
3657 Context.getCanonicalType(ArgFunctionType)))
3658 return TDK_MiscellaneousDeductionFailure;
3659 else if(!InOverloadResolution &&
3660 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3661 return TDK_MiscellaneousDeductionFailure;
3662 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003663
3664 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003665}
3666
Simon Pilgrim728134c2016-08-12 11:43:57 +00003667/// \brief Given a function declaration (e.g. a generic lambda conversion
3668/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003669/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3670/// to replace 'auto' with and not the actual result type you want
3671/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003672static inline void
3673SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003674 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003675 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003676 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003677 assert(AutoResultType->getContainedAutoType());
3678 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003679 TypeToReplaceAutoWith);
3680 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3681}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003682
Simon Pilgrim728134c2016-08-12 11:43:57 +00003683/// \brief Given a specialized conversion operator of a generic lambda
3684/// create the corresponding specializations of the call operator and
3685/// the static-invoker. If the return type of the call operator is auto,
3686/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003687/// return type of the destination function ptr.
3688
Simon Pilgrim728134c2016-08-12 11:43:57 +00003689static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003690SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3691 CXXConversionDecl *ConversionSpecialized,
3692 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3693 QualType ReturnTypeOfDestFunctionPtr,
3694 TemplateDeductionInfo &TDInfo,
3695 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003696
Faisal Vali2b3a3012013-10-24 23:40:02 +00003697 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003698 assert(LambdaClass && LambdaClass->isGenericLambda());
3699
Faisal Vali2b3a3012013-10-24 23:40:02 +00003700 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003701 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003702 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003703 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003704
3705 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003706 CallOpGeneric->getDescribedFunctionTemplate();
3707
Craig Topperc3ec1492014-05-26 06:22:03 +00003708 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003709 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003710 // generic lambda's call operator.
3711 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003712 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3713 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714 0, CallOpSpecialized, TDInfo))
3715 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003716
Faisal Vali2b3a3012013-10-24 23:40:02 +00003717 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003718 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3719 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003720 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003721 CallOpSpecialized->getPointOfInstantiation(),
3722 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003723
Faisal Vali2b3a3012013-10-24 23:40:02 +00003724 // Check to see if the return type of the destination ptr-to-function
3725 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003726 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 ReturnTypeOfDestFunctionPtr))
3728 return Sema::TDK_NonDeducedMismatch;
3729 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003730 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003731 // specialized our corresponding call operator, we are ready to
3732 // specialize the static invoker with the deduced arguments of our
3733 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003734 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3736 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3737
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003738#ifndef NDEBUG
3739 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3740#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003741 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003742 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003743 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003744 "If the call operator succeeded so should the invoker!");
3745 // Set the result type to match the corresponding call operator
3746 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003747 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3748 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003749 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003750 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 // to substitute into the 'auto' of the invoker and conversion
3752 // function.
3753 // For e.g.
3754 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3755 // We don't want to subst 'int*' into 'auto' to get int**.
3756
Alp Toker314cc812014-01-25 16:55:45 +00003757 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3758 ->getContainedAutoType()
3759 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003760 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3761 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003762 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003763 TypeToReplaceAutoWith, S);
3764 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003765
Faisal Vali2b3a3012013-10-24 23:40:02 +00003766 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003767 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003768 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003769 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003770 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3771 getType().getTypePtr()->castAs<FunctionProtoType>();
3772 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3773 EPI.TypeQuals = 0;
3774 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003775 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 return Sema::TDK_Success;
3777}
Douglas Gregor05155d82009-08-21 23:19:43 +00003778/// \brief Deduce template arguments for a templated conversion
3779/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3780/// conversion function template specialization.
3781Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003782Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003783 QualType ToType,
3784 CXXConversionDecl *&Specialization,
3785 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003786 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003787 return TDK_Invalid;
3788
Faisal Vali2b3a3012013-10-24 23:40:02 +00003789 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003790 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3791
Faisal Vali2b3a3012013-10-24 23:40:02 +00003792 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003793
3794 // Canonicalize the types for deduction.
3795 QualType P = Context.getCanonicalType(FromType);
3796 QualType A = Context.getCanonicalType(ToType);
3797
Douglas Gregord99609a2011-03-06 09:03:20 +00003798 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003799 // If P is a reference type, the type referred to by P is used for
3800 // type deduction.
3801 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3802 P = PRef->getPointeeType();
3803
Douglas Gregord99609a2011-03-06 09:03:20 +00003804 // C++0x [temp.deduct.conv]p4:
3805 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003806 // for type deduction.
3807 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003808 A = ARef->getPointeeType().getUnqualifiedType();
3809 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003810 //
Mike Stump11289f42009-09-09 15:08:12 +00003811 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003812 else {
3813 assert(!A->isReferenceType() && "Reference types were handled above");
3814
3815 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003816 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003817 // of P for type deduction; otherwise,
3818 if (P->isArrayType())
3819 P = Context.getArrayDecayedType(P);
3820 // - If P is a function type, the pointer type produced by the
3821 // function-to-pointer standard conversion (4.3) is used in
3822 // place of P for type deduction; otherwise,
3823 else if (P->isFunctionType())
3824 P = Context.getPointerType(P);
3825 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003826 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003827 else
3828 P = P.getUnqualifiedType();
3829
Douglas Gregord99609a2011-03-06 09:03:20 +00003830 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003831 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003832 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003833 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003834 A = A.getUnqualifiedType();
3835 }
3836
Eli Friedman77dcc722012-02-08 03:07:05 +00003837 // Unevaluated SFINAE context.
3838 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003839 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003840
3841 // C++ [temp.deduct.conv]p1:
3842 // Template argument deduction is done by comparing the return
3843 // type of the template conversion function (call it P) with the
3844 // type that is required as the result of the conversion (call it
3845 // A) as described in 14.8.2.4.
3846 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003847 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003848 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003849 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003850
3851 // C++0x [temp.deduct.conv]p4:
3852 // In general, the deduction process attempts to find template
3853 // argument values that will make the deduced A identical to
3854 // A. However, there are two cases that allow a difference:
3855 unsigned TDF = 0;
3856 // - If the original A is a reference type, A can be more
3857 // cv-qualified than the deduced A (i.e., the type referred to
3858 // by the reference)
3859 if (ToType->isReferenceType())
3860 TDF |= TDF_ParamWithReferenceType;
3861 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003862 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003863 // conversion.
3864 //
3865 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3866 // both P and A are pointers or member pointers. In this case, we
3867 // just ignore cv-qualifiers completely).
3868 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003869 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003870 TDF |= TDF_IgnoreQualifiers;
3871 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003872 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3873 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003874 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003875
3876 // Create an Instantiation Scope for finalizing the operator.
3877 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003878 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003879 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003880 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003881 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003882 ConversionSpecialized, Info);
3883 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3884
3885 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003886 // to a ptr-to-function, use the deduced arguments from the conversion
3887 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003888 // e.g., int (*fp)(int) = [](auto a) { return a; };
3889 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003890
Faisal Vali2b3a3012013-10-24 23:40:02 +00003891 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003892 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003893 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003894 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003895 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003896 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003897 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003898 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3899
Simon Pilgrim728134c2016-08-12 11:43:57 +00003900 // Create the corresponding specializations of the call operator and
3901 // the static-invoker; and if the return type is auto,
3902 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003903 // DestFunctionPtrReturnType.
3904 // For instance:
3905 // auto L = [](auto a) { return f(a); };
3906 // int (*fp)(int) = L;
3907 // char (*fp2)(int) = L; <-- Not OK.
3908
3909 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003910 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003911 Info, *this);
3912 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003913 return Result;
3914}
3915
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003916/// \brief Deduce template arguments for a function template when there is
3917/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3918///
3919/// \param FunctionTemplate the function template for which we are performing
3920/// template argument deduction.
3921///
James Dennett18348b62012-06-22 08:52:37 +00003922/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003923/// arguments.
3924///
3925/// \param Specialization if template argument deduction was successful,
3926/// this will be set to the function template specialization produced by
3927/// template argument deduction.
3928///
3929/// \param Info the argument will be updated to provide additional information
3930/// about template argument deduction.
3931///
3932/// \returns the result of template argument deduction.
3933Sema::TemplateDeductionResult
3934Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003935 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003936 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003937 TemplateDeductionInfo &Info,
3938 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003939 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003940 QualType(), Specialization, Info,
3941 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003942}
3943
Richard Smith30482bc2011-02-20 03:19:35 +00003944namespace {
3945 /// Substitute the 'auto' type specifier within a type for a given replacement
3946 /// type.
3947 class SubstituteAutoTransform :
3948 public TreeTransform<SubstituteAutoTransform> {
3949 QualType Replacement;
3950 public:
Nico Weberc153d242014-07-28 00:02:09 +00003951 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3952 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3953 Replacement(Replacement) {}
3954
Richard Smith30482bc2011-02-20 03:19:35 +00003955 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3956 // If we're building the type pattern to deduce against, don't wrap the
3957 // substituted type in an AutoType. Certain template deduction rules
3958 // apply only when a template type parameter appears directly (and not if
3959 // the parameter is found through desugaring). For instance:
3960 // auto &&lref = lvalue;
3961 // must transform into "rvalue reference to T" not "rvalue reference to
3962 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003963 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003964 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003965 TemplateTypeParmTypeLoc NewTL =
3966 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003967 NewTL.setNameLoc(TL.getNameLoc());
3968 return Result;
3969 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003970 bool Dependent =
3971 !Replacement.isNull() && Replacement->isDependentType();
3972 QualType Result =
3973 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003974 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003975 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003976 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3977 NewTL.setNameLoc(TL.getNameLoc());
3978 return Result;
3979 }
3980 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003981
3982 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3983 // Lambdas never need to be transformed.
3984 return E;
3985 }
Richard Smith061f1e22013-04-30 21:23:01 +00003986
Richard Smith2a7d4812013-05-04 07:00:32 +00003987 QualType Apply(TypeLoc TL) {
3988 // Create some scratch storage for the transformed type locations.
3989 // FIXME: We're just going to throw this information away. Don't build it.
3990 TypeLocBuilder TLB;
3991 TLB.reserve(TL.getFullDataSize());
3992 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003993 }
Richard Smith30482bc2011-02-20 03:19:35 +00003994 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003995}
Richard Smith30482bc2011-02-20 03:19:35 +00003996
Richard Smith2a7d4812013-05-04 07:00:32 +00003997Sema::DeduceAutoResult
3998Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3999 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
4000}
4001
Richard Smith061f1e22013-04-30 21:23:01 +00004002/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004003///
4004/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004005/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004006/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004007/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00004008Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00004009Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00004010 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004011 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4012 if (NonPlaceholder.isInvalid())
4013 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004014 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004015 }
4016
Richard Smith2a7d4812013-05-04 07:00:32 +00004017 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004018 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004019 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004020 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004021 }
4022
Richard Smith74aeef52013-04-26 16:15:35 +00004023 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4024 // Since 'decltype(auto)' can only occur at the top of the type, we
4025 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004026 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004027 if (AT->isDecltypeAuto()) {
4028 if (isa<InitListExpr>(Init)) {
4029 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4030 return DAR_FailedAlreadyDiagnosed;
4031 }
4032
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004033 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004034 if (Deduced.isNull())
4035 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004036 // FIXME: Support a non-canonical deduced type for 'auto'.
4037 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004038 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004039 if (Result.isNull())
4040 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004041 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004042 } else if (!getLangOpts().CPlusPlus) {
4043 if (isa<InitListExpr>(Init)) {
4044 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4045 return DAR_FailedAlreadyDiagnosed;
4046 }
Richard Smith74aeef52013-04-26 16:15:35 +00004047 }
4048 }
4049
Richard Smith30482bc2011-02-20 03:19:35 +00004050 SourceLocation Loc = Init->getExprLoc();
4051
4052 LocalInstantiationScope InstScope(*this);
4053
4054 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004055 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004056 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4057 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004058 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4059 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004060 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4061 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004062
Richard Smith061f1e22013-04-30 21:23:01 +00004063 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4064 assert(!FuncParam.isNull() &&
4065 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004066
4067 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004068 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004069 Deduced.resize(1);
4070 QualType InitType = Init->getType();
4071 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004072
Craig Toppere6706e42012-09-19 02:26:47 +00004073 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004074
Richard Smith74801c82012-07-08 04:13:07 +00004075 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004076 if (InitList) {
4077 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004078 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4079 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004080 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004081 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004082 }
4083 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004084 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4085 Diag(Loc, diag::err_auto_bitfield);
4086 return DAR_FailedAlreadyDiagnosed;
4087 }
4088
James Y Knight7a22b242015-08-06 20:26:32 +00004089 if (AdjustFunctionParmAndArgTypesForDeduction(
4090 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004091 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004092
James Y Knight7a22b242015-08-06 20:26:32 +00004093 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4094 FuncParam, InitType, Info, Deduced,
4095 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004096 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004097 }
Richard Smith30482bc2011-02-20 03:19:35 +00004098
Eli Friedmane4310952012-11-06 23:56:42 +00004099 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004100 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004101
Eli Friedmane4310952012-11-06 23:56:42 +00004102 QualType DeducedType = Deduced[0].getAsType();
4103
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004104 if (InitList) {
4105 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4106 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004107 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004108 }
4109
Richard Smith061f1e22013-04-30 21:23:01 +00004110 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004111 if (Result.isNull())
4112 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004113
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004114 // Check that the deduced argument type is compatible with the original
4115 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004116 if (!InitList && !Result.isNull() &&
4117 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004118 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004119 Result)) {
4120 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004121 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004122 }
4123
Sebastian Redl09edce02012-01-23 22:09:39 +00004124 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004125}
4126
Simon Pilgrim728134c2016-08-12 11:43:57 +00004127QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004128 QualType TypeToReplaceAuto) {
4129 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4130 TransformType(TypeWithAuto);
4131}
4132
Simon Pilgrim728134c2016-08-12 11:43:57 +00004133TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004134 QualType TypeToReplaceAuto) {
4135 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4136 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004137}
4138
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004139void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4140 if (isa<InitListExpr>(Init))
4141 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004142 VDecl->isInitCapture()
4143 ? diag::err_init_capture_deduction_failure_from_init_list
4144 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004145 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4146 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004147 Diag(VDecl->getLocation(),
4148 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4149 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004150 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4151 << Init->getSourceRange();
4152}
4153
Richard Smith2a7d4812013-05-04 07:00:32 +00004154bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4155 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004156 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004157
4158 if (FD->getTemplateInstantiationPattern())
4159 InstantiateFunctionDefinition(Loc, FD);
4160
Alp Toker314cc812014-01-25 16:55:45 +00004161 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004162 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4163 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4164 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4165 }
4166
4167 return StillUndeduced;
4168}
4169
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004170static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004171MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004172 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004173 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004174 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
4176/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004177static void
4178AddImplicitObjectParameterType(ASTContext &Context,
4179 CXXMethodDecl *Method,
4180 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004181 // C++11 [temp.func.order]p3:
4182 // [...] The new parameter is of type "reference to cv A," where cv are
4183 // the cv-qualifiers of the function template (if any) and A is
4184 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004185 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004186 // The standard doesn't say explicitly, but we pick the appropriate kind of
4187 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004188 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4189 ArgTy = Context.getQualifiedType(ArgTy,
4190 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004191 if (Method->getRefQualifier() == RQ_RValue)
4192 ArgTy = Context.getRValueReferenceType(ArgTy);
4193 else
4194 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004195 ArgTypes.push_back(ArgTy);
4196}
4197
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004198/// \brief Determine whether the function template \p FT1 is at least as
4199/// specialized as \p FT2.
4200static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004201 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004202 FunctionTemplateDecl *FT1,
4203 FunctionTemplateDecl *FT2,
4204 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004205 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004206 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004208 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4209 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004211 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4212 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004213 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004214 Deduced.resize(TemplateParams->size());
4215
4216 // C++0x [temp.deduct.partial]p3:
4217 // The types used to determine the ordering depend on the context in which
4218 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004219 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004220 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004221 switch (TPOC) {
4222 case TPOC_Call: {
4223 // - In the context of a function call, the function parameter types are
4224 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004225 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4226 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004227
Eli Friedman3b5774a2012-09-19 23:27:04 +00004228 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004229 // [...] If only one of the function templates is a non-static
4230 // member, that function template is considered to have a new
4231 // first parameter inserted in its function parameter list. The
4232 // new parameter is of type "reference to cv A," where cv are
4233 // the cv-qualifiers of the function template (if any) and A is
4234 // the class of which the function template is a member.
4235 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004236 // Note that we interpret this to mean "if one of the function
4237 // templates is a non-static member and the other is a non-member";
4238 // otherwise, the ordering rules for static functions against non-static
4239 // functions don't make any sense.
4240 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004241 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4242 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004243 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004244
Richard Smithe5b52202013-09-11 00:52:39 +00004245 unsigned NumComparedArguments = NumCallArguments1;
4246
4247 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004248 // Compare 'this' from Method1 against first parameter from Method2.
4249 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4250 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004251 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004252 // Compare 'this' from Method2 against first parameter from Method1.
4253 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004254 }
4255
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004256 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004257 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004258 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004259 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Douglas Gregorb837ea42011-01-11 17:34:58 +00004261 // C++ [temp.func.order]p5:
4262 // The presence of unused ellipsis and default arguments has no effect on
4263 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004264 if (Args1.size() > NumComparedArguments)
4265 Args1.resize(NumComparedArguments);
4266 if (Args2.size() > NumComparedArguments)
4267 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004268 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4269 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004270 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004271 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004273 break;
4274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 case TPOC_Conversion:
4277 // - In the context of a call to a conversion operator, the return types
4278 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004279 if (DeduceTemplateArgumentsByTypeMatch(
4280 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4281 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004282 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 return false;
4284 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004287 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004288 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004289 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4290 FD2->getType(), FD1->getType(),
4291 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004292 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004293 return false;
4294 break;
4295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004297 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 // In most cases, all template parameters must have values in order for
4299 // deduction to succeed, but for partial ordering purposes a template
4300 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004301 // types being used for partial ordering. [ Note: a template parameter used
4302 // in a non-deduced context is considered used. -end note]
4303 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4304 for (; ArgIdx != NumArgs; ++ArgIdx)
4305 if (Deduced[ArgIdx].isNull())
4306 break;
4307
4308 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004310 // as FT2.
4311 return true;
4312 }
4313
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004314 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004315 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004316 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004317 case TPOC_Call:
4318 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4319 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004320 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004321 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004322 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004324 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004325 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4326 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004329 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004330 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004331 TemplateParams->getDepth(),
4332 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004333 break;
4334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004336 for (; ArgIdx != NumArgs; ++ArgIdx)
4337 // If this argument had no value deduced but was used in one of the types
4338 // used for partial ordering, then deduction fails.
4339 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4340 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004342 return true;
4343}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregorcef1a032011-01-16 16:03:23 +00004345/// \brief Determine whether this a function template whose parameter-type-list
4346/// ends with a function parameter pack.
4347static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4348 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4349 unsigned NumParams = Function->getNumParams();
4350 if (NumParams == 0)
4351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Douglas Gregorcef1a032011-01-16 16:03:23 +00004353 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4354 if (!Last->isParameterPack())
4355 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Douglas Gregorcef1a032011-01-16 16:03:23 +00004357 // Make sure that no previous parameter is a parameter pack.
4358 while (--NumParams > 0) {
4359 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4360 return false;
4361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362
Douglas Gregorcef1a032011-01-16 16:03:23 +00004363 return true;
4364}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregorbe999392009-09-15 16:23:51 +00004366/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004367/// to the rules of function template partial ordering (C++ [temp.func.order]).
4368///
4369/// \param FT1 the first function template
4370///
4371/// \param FT2 the second function template
4372///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004373/// \param TPOC the context in which we are performing partial ordering of
4374/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004375///
Richard Smithe5b52202013-09-11 00:52:39 +00004376/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4377/// only when \c TPOC is \c TPOC_Call.
4378///
4379/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4380/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004381///
Douglas Gregorbe999392009-09-15 16:23:51 +00004382/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004383/// template is more specialized, returns NULL.
4384FunctionTemplateDecl *
4385Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4386 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004387 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004388 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004389 unsigned NumCallArguments1,
4390 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004392 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004394 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004396 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004397 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004399 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004400 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004401
Douglas Gregorcef1a032011-01-16 16:03:23 +00004402 // FIXME: This mimics what GCC implements, but doesn't match up with the
4403 // proposed resolution for core issue 692. This area needs to be sorted out,
4404 // but for now we attempt to maintain compatibility.
4405 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4406 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4407 if (Variadic1 != Variadic2)
4408 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Craig Topperc3ec1492014-05-26 06:22:03 +00004410 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004411}
Douglas Gregor9b146582009-07-08 20:55:45 +00004412
Douglas Gregor450f00842009-09-25 18:43:00 +00004413/// \brief Determine if the two templates are equivalent.
4414static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4415 if (T1 == T2)
4416 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregor450f00842009-09-25 18:43:00 +00004418 if (!T1 || !T2)
4419 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregor450f00842009-09-25 18:43:00 +00004421 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4422}
4423
4424/// \brief Retrieve the most specialized of the given function template
4425/// specializations.
4426///
John McCall58cc69d2010-01-27 01:50:18 +00004427/// \param SpecBegin the start iterator of the function template
4428/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004429///
John McCall58cc69d2010-01-27 01:50:18 +00004430/// \param SpecEnd the end iterator of the function template
4431/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004432///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004434/// diagnostic should occur.
4435///
4436/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4437/// no matching candidates.
4438///
4439/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4440/// occurs.
4441///
4442/// \param CandidateDiag partial diagnostic used for each function template
4443/// specialization that is a candidate in the ambiguous ordering. One parameter
4444/// in this diagnostic should be unbound, which will correspond to the string
4445/// describing the template arguments for the function template specialization.
4446///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004448/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004449UnresolvedSetIterator Sema::getMostSpecialized(
4450 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4451 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004452 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4453 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4454 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004455 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004456 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004457 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004458 FailedCandidates.NoteCandidates(*this, Loc);
4459 }
John McCall58cc69d2010-01-27 01:50:18 +00004460 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462
4463 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004464 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465
Douglas Gregor450f00842009-09-25 18:43:00 +00004466 // Find the function template that is better than all of the templates it
4467 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004468 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004470 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004471 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004472 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4473 FunctionTemplateDecl *Challenger
4474 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004475 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004476 if (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 Challenger)) {
4479 Best = I;
4480 BestTemplate = Challenger;
4481 }
4482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483
Douglas Gregor450f00842009-09-25 18:43:00 +00004484 // Make sure that the "best" function template is more specialized than all
4485 // of the others.
4486 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004487 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4488 FunctionTemplateDecl *Challenger
4489 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004490 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004492 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004493 BestTemplate)) {
4494 Ambiguous = true;
4495 break;
4496 }
4497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor450f00842009-09-25 18:43:00 +00004499 if (!Ambiguous) {
4500 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004501 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor450f00842009-09-25 18:43:00 +00004504 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004505 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004506 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507
Richard Smithb875c432013-05-04 01:51:08 +00004508 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004509 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4510 PartialDiagnostic PD = CandidateDiag;
4511 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004512 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004513 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004514 if (!TargetType.isNull())
4515 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4516 TargetType);
4517 Diag((*I)->getLocation(), PD);
4518 }
Richard Smithb875c432013-05-04 01:51:08 +00004519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
John McCall58cc69d2010-01-27 01:50:18 +00004521 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004522}
4523
Douglas Gregorbe999392009-09-15 16:23:51 +00004524/// \brief Returns the more specialized class template partial specialization
4525/// according to the rules of partial ordering of class template partial
4526/// specializations (C++ [temp.class.order]).
4527///
4528/// \param PS1 the first class template partial specialization
4529///
4530/// \param PS2 the second class template partial specialization
4531///
4532/// \returns the more specialized class template partial specialization. If
4533/// neither partial specialization is more specialized, returns NULL.
4534ClassTemplatePartialSpecializationDecl *
4535Sema::getMoreSpecializedPartialSpecialization(
4536 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004537 ClassTemplatePartialSpecializationDecl *PS2,
4538 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004539 // C++ [temp.class.order]p1:
4540 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 // specialized as the second if, given the following rewrite to two
4542 // function templates, the first function template is at least as
4543 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004544 // templates (14.6.6.2):
4545 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546 // first partial specialization and has a single function parameter
4547 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004548 // arguments of the first partial specialization, and
4549 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 // second partial specialization and has a single function parameter
4551 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004552 // arguments of the second partial specialization.
4553 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004554 // Rather than synthesize function templates, we merely perform the
4555 // equivalent partial ordering by performing deduction directly on
4556 // the template arguments of the class template partial
4557 // specializations. This computation is slightly simpler than the
4558 // general problem of function template partial ordering, because
4559 // class template partial specializations are more constrained. We
4560 // know that every template parameter is deducible from the class
4561 // template partial specialization's template arguments, for
4562 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004563 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004564 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004565
4566 QualType PT1 = PS1->getInjectedSpecializationType();
4567 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Douglas Gregorbe999392009-09-15 16:23:51 +00004569 // Determine whether PS1 is at least as specialized as PS2
4570 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004571 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4572 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004573 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004574 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004575 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004576 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004577 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004578 Better1 = !::FinishTemplateArgumentDeduction(
4579 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4580 }
4581
4582 // Determine whether PS2 is at least as specialized as PS1
4583 Deduced.clear();
4584 Deduced.resize(PS1->getTemplateParameters()->size());
4585 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4586 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004587 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004588 if (Better2) {
4589 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4590 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004591 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004592 Better2 = !::FinishTemplateArgumentDeduction(
4593 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4594 }
4595
4596 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004597 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004598
4599 return Better1 ? PS1 : PS2;
4600}
4601
Larisse Voufo30616382013-08-23 22:21:36 +00004602/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4603/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4604/// VarTemplate(Partial)SpecializationDecl with a new data
4605/// structure Template(Partial)SpecializationDecl, and
4606/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004607VarTemplatePartialSpecializationDecl *
4608Sema::getMoreSpecializedPartialSpecialization(
4609 VarTemplatePartialSpecializationDecl *PS1,
4610 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4611 SmallVector<DeducedTemplateArgument, 4> Deduced;
4612 TemplateDeductionInfo Info(Loc);
4613
Richard Smithf04fd0b2013-12-12 23:14:16 +00004614 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004615 "the partial specializations being compared should specialize"
4616 " the same template.");
4617 TemplateName Name(PS1->getSpecializedTemplate());
4618 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4619 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004620 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004621 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004622 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004623
4624 // Determine whether PS1 is at least as specialized as PS2
4625 Deduced.resize(PS2->getTemplateParameters()->size());
4626 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4627 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004628 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004629 if (Better1) {
4630 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4631 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004632 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4634 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004635 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637
Douglas Gregorbe999392009-09-15 16:23:51 +00004638 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004639 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004640 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004641 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4642 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004643 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004644 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004645 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004646 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004647 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4649 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004650 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652
Douglas Gregorbe999392009-09-15 16:23:51 +00004653 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004654 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655
Douglas Gregorbe999392009-09-15 16:23:51 +00004656 return Better1? PS1 : PS2;
4657}
4658
Mike Stump11289f42009-09-09 15:08:12 +00004659static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004660MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004661 const TemplateArgument &TemplateArg,
4662 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004663 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004664 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004665
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004666/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004667/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004668static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004669MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004670 const Expr *E,
4671 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004672 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004673 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004674 // We can deduce from a pack expansion.
4675 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4676 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Richard Smith34349002012-07-09 03:07:20 +00004678 // Skip through any implicit casts we added while type-checking, and any
4679 // substitutions performed by template alias expansion.
4680 while (1) {
4681 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4682 E = ICE->getSubExpr();
4683 else if (const SubstNonTypeTemplateParmExpr *Subst =
4684 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4685 E = Subst->getReplacement();
4686 else
4687 break;
4688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689
4690 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004691 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004692 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004693 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004694 return;
4695
Mike Stump11289f42009-09-09 15:08:12 +00004696 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004697 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4698 if (!NTTP)
4699 return;
4700
Douglas Gregor21610382009-10-29 00:04:11 +00004701 if (NTTP->getDepth() == Depth)
4702 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004703}
4704
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004705/// \brief Mark the template parameters that are used by the given
4706/// nested name specifier.
4707static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004708MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004709 NestedNameSpecifier *NNS,
4710 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004711 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004712 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004713 if (!NNS)
4714 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004716 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004717 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004718 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004719 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004720}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004722/// \brief Mark the template parameters that are used by the given
4723/// template name.
4724static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004725MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004726 TemplateName Name,
4727 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004728 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004729 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004730 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4731 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004732 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4733 if (TTP->getDepth() == Depth)
4734 Used[TTP->getIndex()] = true;
4735 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004736 return;
4737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004739 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004741 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004742 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004743 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004744 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004745}
4746
4747/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004748/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004749static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004750MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004751 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004752 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004753 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004754 if (T.isNull())
4755 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004756
Douglas Gregor91772d12009-06-13 00:26:55 +00004757 // Non-dependent types have nothing deducible
4758 if (!T->isDependentType())
4759 return;
4760
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004761 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004762 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004763 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004764 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004765 cast<PointerType>(T)->getPointeeType(),
4766 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004767 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004768 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004769 break;
4770
4771 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004772 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004773 cast<BlockPointerType>(T)->getPointeeType(),
4774 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004775 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004776 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004777 break;
4778
4779 case Type::LValueReference:
4780 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004781 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004782 cast<ReferenceType>(T)->getPointeeType(),
4783 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004784 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004785 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004786 break;
4787
4788 case Type::MemberPointer: {
4789 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004790 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004791 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004792 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004793 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004794 break;
4795 }
4796
4797 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004798 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004799 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004800 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004801 // Fall through to check the element type
4802
4803 case Type::ConstantArray:
4804 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004805 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004807 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004808 break;
4809
4810 case Type::Vector:
4811 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004812 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004813 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004814 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004815 break;
4816
Douglas Gregor758a8692009-06-17 21:51:59 +00004817 case Type::DependentSizedExtVector: {
4818 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004819 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004820 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004821 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004822 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004823 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004824 break;
4825 }
4826
Douglas Gregor91772d12009-06-13 00:26:55 +00004827 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004828 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004829 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4830 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004831 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4832 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004833 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004834 break;
4835 }
4836
Douglas Gregor21610382009-10-29 00:04:11 +00004837 case Type::TemplateTypeParm: {
4838 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4839 if (TTP->getDepth() == Depth)
4840 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004841 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004842 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004843
Douglas Gregorfb322d82011-01-14 05:11:40 +00004844 case Type::SubstTemplateTypeParmPack: {
4845 const SubstTemplateTypeParmPackType *Subst
4846 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004847 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004848 QualType(Subst->getReplacedParameter(), 0),
4849 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004850 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004851 OnlyDeduced, Depth, Used);
4852 break;
4853 }
4854
John McCall2408e322010-04-27 00:57:59 +00004855 case Type::InjectedClassName:
4856 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4857 // fall through
4858
Douglas Gregor91772d12009-06-13 00:26:55 +00004859 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004860 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004861 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004862 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004863 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004864
Douglas Gregord0ad2942010-12-23 01:24:45 +00004865 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004866 // If the template argument list of P contains a pack expansion that is
4867 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004868 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004870 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4871 break;
4872
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004873 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004875 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004876 break;
4877 }
4878
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004879 case Type::Complex:
4880 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004881 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004882 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004883 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004884 break;
4885
Eli Friedman0dfb8892011-10-06 23:00:33 +00004886 case Type::Atomic:
4887 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004888 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004889 cast<AtomicType>(T)->getValueType(),
4890 OnlyDeduced, Depth, Used);
4891 break;
4892
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004893 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004894 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004895 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004896 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004897 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004898 break;
4899
John McCallc392f372010-06-11 00:33:02 +00004900 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004901 // C++14 [temp.deduct.type]p5:
4902 // The non-deduced contexts are:
4903 // -- The nested-name-specifier of a type that was specified using a
4904 // qualified-id
4905 //
4906 // C++14 [temp.deduct.type]p6:
4907 // When a type name is specified in a way that includes a non-deduced
4908 // context, all of the types that comprise that type name are also
4909 // non-deduced.
4910 if (OnlyDeduced)
4911 break;
4912
John McCallc392f372010-06-11 00:33:02 +00004913 const DependentTemplateSpecializationType *Spec
4914 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Richard Smith50d5b972015-12-30 20:56:05 +00004916 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4917 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004918
John McCallc392f372010-06-11 00:33:02 +00004919 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004920 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004921 Used);
4922 break;
4923 }
4924
John McCallbd8d9bd2010-03-01 23:49:17 +00004925 case Type::TypeOf:
4926 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004928 cast<TypeOfType>(T)->getUnderlyingType(),
4929 OnlyDeduced, Depth, Used);
4930 break;
4931
4932 case Type::TypeOfExpr:
4933 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004934 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004935 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4936 OnlyDeduced, Depth, Used);
4937 break;
4938
4939 case Type::Decltype:
4940 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004941 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004942 cast<DecltypeType>(T)->getUnderlyingExpr(),
4943 OnlyDeduced, Depth, Used);
4944 break;
4945
Alexis Hunte852b102011-05-24 22:41:36 +00004946 case Type::UnaryTransform:
4947 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004948 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004949 cast<UnaryTransformType>(T)->getUnderlyingType(),
4950 OnlyDeduced, Depth, Used);
4951 break;
4952
Douglas Gregord2fa7662010-12-20 02:24:11 +00004953 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004954 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004955 cast<PackExpansionType>(T)->getPattern(),
4956 OnlyDeduced, Depth, Used);
4957 break;
4958
Richard Smith30482bc2011-02-20 03:19:35 +00004959 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004960 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004961 cast<AutoType>(T)->getDeducedType(),
4962 OnlyDeduced, Depth, Used);
4963
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004964 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004965 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004966 case Type::VariableArray:
4967 case Type::FunctionNoProto:
4968 case Type::Record:
4969 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004970 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004971 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004972 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004973 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004974 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004975#define TYPE(Class, Base)
4976#define ABSTRACT_TYPE(Class, Base)
4977#define DEPENDENT_TYPE(Class, Base)
4978#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4979#include "clang/AST/TypeNodes.def"
4980 break;
4981 }
4982}
4983
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004984/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004985/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004986static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004987MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004988 const TemplateArgument &TemplateArg,
4989 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004990 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004991 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 switch (TemplateArg.getKind()) {
4993 case TemplateArgument::Null:
4994 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004995 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004996 break;
Mike Stump11289f42009-09-09 15:08:12 +00004997
Eli Friedmanb826a002012-09-26 02:36:12 +00004998 case TemplateArgument::NullPtr:
4999 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5000 Depth, Used);
5001 break;
5002
Douglas Gregor91772d12009-06-13 00:26:55 +00005003 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005004 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005005 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005006 break;
5007
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005008 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005009 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005010 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005012 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005013 break;
5014
5015 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005016 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005017 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005018 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Anders Carlssonbc343912009-06-15 17:04:53 +00005020 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005021 for (const auto &P : TemplateArg.pack_elements())
5022 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005023 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005024 }
5025}
5026
James Dennett41725122012-06-22 10:16:05 +00005027/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005028/// template argument list.
5029///
5030/// \param TemplateArgs the template argument list from which template
5031/// parameters will be deduced.
5032///
James Dennett41725122012-06-22 10:16:05 +00005033/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005034/// to indicate when the corresponding template parameter will be
5035/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005036void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005037Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005038 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005039 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005040 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041 // If the template argument list of P contains a pack expansion that is not
5042 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005043 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005045 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5046 return;
5047
Douglas Gregor91772d12009-06-13 00:26:55 +00005048 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005049 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005050 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005051}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005052
5053/// \brief Marks all of the template parameters that will be deduced by a
5054/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005055void Sema::MarkDeducedTemplateParameters(
5056 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5057 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005059 = FunctionTemplate->getTemplateParameters();
5060 Deduced.clear();
5061 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregorce23bae2009-09-18 23:21:38 +00005063 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5064 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005065 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005066 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005067}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005068
5069bool hasDeducibleTemplateParameters(Sema &S,
5070 FunctionTemplateDecl *FunctionTemplate,
5071 QualType T) {
5072 if (!T->isDependentType())
5073 return false;
5074
5075 TemplateParameterList *TemplateParams
5076 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005077 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005078 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005079 Deduced);
5080
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005081 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005082}