blob: 0e20ef2441d0b379b7bb468d118c07952f896310 [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 Smith5f274382016-09-28 23:55:27 +0000103 bool PartialOrdering = false,
104 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000105
106static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000107DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000108 ArrayRef<TemplateArgument> Params,
109 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000110 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
112 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000113
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000114/// \brief If the given expression is of a form that permits the deduction
115/// of a non-type template parameter, return the declaration of that
116/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000117static NonTypeTemplateParmDecl *
118getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000119 // If we are within an alias template, the expression may have undergone
120 // any number of parameter substitutions already.
121 while (1) {
122 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
123 E = IC->getSubExpr();
124 else if (SubstNonTypeTemplateParmExpr *Subst =
125 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
126 E = Subst->getReplacement();
127 else
128 break;
129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000131 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000132 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
133 if (NTTP->getDepth() == Info.getDeducedDepth())
134 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000135
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000137}
138
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139/// \brief Determine whether two declaration pointers refer to the same
140/// declaration.
141static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000142 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
143 X = NX->getUnderlyingDecl();
144 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
145 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000146
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000147 return X->getCanonicalDecl() == Y->getCanonicalDecl();
148}
149
150/// \brief Verify that the given, deduced template arguments are compatible.
151///
152/// \returns The deduced template argument, or a NULL template argument if
153/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000155checkDeducedTemplateArguments(ASTContext &Context,
156 const DeducedTemplateArgument &X,
157 const DeducedTemplateArgument &Y) {
158 // We have no deduction for one or both of the arguments; they're compatible.
159 if (X.isNull())
160 return Y;
161 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000162 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000163
Richard Smith593d6a12016-12-23 01:30:39 +0000164 // If we have two non-type template argument values deduced for the same
165 // parameter, they must both match the type of the parameter, and thus must
166 // match each other's type. As we're only keeping one of them, we must check
167 // for that now. The exception is that if either was deduced from an array
168 // bound, the type is permitted to differ.
169 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
170 QualType XType = X.getNonTypeTemplateArgumentType();
171 if (!XType.isNull()) {
172 QualType YType = Y.getNonTypeTemplateArgumentType();
173 if (YType.isNull() || !Context.hasSameType(XType, YType))
174 return DeducedTemplateArgument();
175 }
176 }
177
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000178 switch (X.getKind()) {
179 case TemplateArgument::Null:
180 llvm_unreachable("Non-deduced template arguments handled above");
181
182 case TemplateArgument::Type:
183 // If two template type arguments have the same type, they're compatible.
184 if (Y.getKind() == TemplateArgument::Type &&
185 Context.hasSameType(X.getAsType(), Y.getAsType()))
186 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
Richard Smith5f274382016-09-28 23:55:27 +0000188 // If one of the two arguments was deduced from an array bound, the other
189 // supersedes it.
190 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
191 return X.wasDeducedFromArrayBound() ? Y : X;
192
193 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 case TemplateArgument::Integral:
197 // If we deduced a constant in one case and either a dependent expression or
198 // declaration in another case, keep the integral constant.
199 // If both are integral constants with the same value, keep that value.
200 if (Y.getKind() == TemplateArgument::Expression ||
201 Y.getKind() == TemplateArgument::Declaration ||
202 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000203 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000204 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000205
206 // All other combinations are incompatible.
207 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000208
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000209 case TemplateArgument::Template:
210 if (Y.getKind() == TemplateArgument::Template &&
211 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
212 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000213
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000215 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000216
217 case TemplateArgument::TemplateExpansion:
218 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 Y.getAsTemplateOrTemplatePattern()))
221 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000223 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000225
Richard Smith593d6a12016-12-23 01:30:39 +0000226 case TemplateArgument::Expression: {
227 if (Y.getKind() != TemplateArgument::Expression)
228 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229
Richard Smith593d6a12016-12-23 01:30:39 +0000230 // Compare the expressions for equality
231 llvm::FoldingSetNodeID ID1, ID2;
232 X.getAsExpr()->Profile(ID1, Context, true);
233 Y.getAsExpr()->Profile(ID2, Context, true);
234 if (ID1 == ID2)
235 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Richard Smith593d6a12016-12-23 01:30:39 +0000237 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000242 assert(!X.wasDeducedFromArrayBound());
243
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000244 // If we deduced a declaration and a dependent expression, keep the
245 // declaration.
246 if (Y.getKind() == TemplateArgument::Expression)
247 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000248
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000249 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000250 // integral constant and whichever type did not come from an array
251 // bound.
252 if (Y.getKind() == TemplateArgument::Integral) {
253 if (Y.wasDeducedFromArrayBound())
254 return TemplateArgument(Context, Y.getAsIntegral(),
255 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000258
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000263 return X;
264
265 // All other combinations are incompatible.
266 return DeducedTemplateArgument();
267
268 case TemplateArgument::NullPtr:
269 // If we deduced a null pointer and a dependent expression, keep the
270 // null pointer.
271 if (Y.getKind() == TemplateArgument::Expression)
272 return X;
273
274 // If we deduced a null pointer and an integral constant, keep the
275 // integral constant.
276 if (Y.getKind() == TemplateArgument::Integral)
277 return Y;
278
Richard Smith593d6a12016-12-23 01:30:39 +0000279 // If we deduced two null pointers, they are the same.
280 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 // All other combinations are incompatible.
284 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 case TemplateArgument::Pack:
287 if (Y.getKind() != TemplateArgument::Pack ||
288 X.pack_size() != Y.pack_size())
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
291 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000292 XAEnd = X.pack_end(),
293 YA = Y.pack_begin();
294 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000295 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000296 if (checkDeducedTemplateArguments(Context,
297 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000298 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
299 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return DeducedTemplateArgument();
301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 return X;
304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305
David Blaikiee4d798f2012-01-20 21:50:17 +0000306 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307}
308
Mike Stump11289f42009-09-09 15:08:12 +0000309/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000310/// as the given deduced template argument. All non-type template parameter
311/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000312static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000313 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000314 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
315 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000316 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000317 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
318 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000319
Richard Smith5d102892016-12-27 03:59:58 +0000320 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
321 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000322 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000323 Info.Param = NTTP;
324 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000325 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000330 if (!S.getLangOpts().CPlusPlus1z)
331 return Sema::TDK_Success;
332
333 // FIXME: It's not clear how deduction of a parameter of reference
334 // type from an argument (of non-reference type) should be performed.
335 // For now, we just remove reference types from both sides and let
336 // the final check for matching types sort out the mess.
337 return DeduceTemplateArgumentsByTypeMatch(
338 S, TemplateParams, NTTP->getType().getNonReferenceType(),
339 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
340 /*PartialOrdering=*/false,
341 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000342}
343
Mike Stump11289f42009-09-09 15:08:12 +0000344/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000345/// from the given integral constant.
346static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
347 Sema &S, TemplateParameterList *TemplateParams,
348 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
349 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
351 return DeduceNonTypeTemplateArgument(
352 S, TemplateParams, NTTP,
353 DeducedTemplateArgument(S.Context, Value, ValueType,
354 DeducedFromArrayBound),
355 ValueType, Info, Deduced);
356}
357
358/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000359/// from the given null pointer template argument type.
360static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000361 Sema &S, TemplateParameterList *TemplateParams,
362 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000363 TemplateDeductionInfo &Info,
364 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
365 Expr *Value =
366 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
367 S.Context.NullPtrTy, NTTP->getLocation()),
368 NullPtrType, CK_NullToPointer)
369 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000370 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
371 DeducedTemplateArgument(Value),
372 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000373}
374
375/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000376/// from the given type- or value-dependent expression.
377///
378/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000379static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
380 Sema &S, TemplateParameterList *TemplateParams,
381 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000383 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
384 "Expression template argument must be type- or value-dependent.");
Richard Smith5d102892016-12-27 03:59:58 +0000385 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
386 DeducedTemplateArgument(Value),
387 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000388}
389
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000390/// \brief Deduce the value of the given non-type template parameter
391/// from the given declaration.
392///
393/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000394static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
395 Sema &S, TemplateParameterList *TemplateParams,
396 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
397 TemplateDeductionInfo &Info,
398 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000400 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000401 return DeduceNonTypeTemplateArgument(
402 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000403}
404
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000406DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000407 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000408 TemplateName Param,
409 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000410 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000411 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000412 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000413 if (!ParamDecl) {
414 // The parameter type is dependent and is not a template template parameter,
415 // so there is nothing that we can deduce.
416 return Sema::TDK_Success;
417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
Douglas Gregoradee3e32009-11-11 23:06:43 +0000419 if (TemplateTemplateParmDecl *TempParam
420 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000421 // If we're not deducing at this depth, there's nothing to deduce.
422 if (TempParam->getDepth() != Info.getDeducedDepth())
423 return Sema::TDK_Success;
424
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000425 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000427 Deduced[TempParam->getIndex()],
428 NewDeduced);
429 if (Result.isNull()) {
430 Info.Param = TempParam;
431 Info.FirstArg = Deduced[TempParam->getIndex()];
432 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000436 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439
Douglas Gregoradee3e32009-11-11 23:06:43 +0000440 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000441 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443
Douglas Gregoradee3e32009-11-11 23:06:43 +0000444 // Mismatch of non-dependent template parameter to argument.
445 Info.FirstArg = TemplateArgument(Param);
446 Info.SecondArg = TemplateArgument(Arg);
447 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000448}
449
Mike Stump11289f42009-09-09 15:08:12 +0000450/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000451/// type (which is a template-id) with the template argument type.
452///
Chandler Carruthc1263112010-02-07 21:33:28 +0000453/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000454///
455/// \param TemplateParams the template parameters that we are deducing
456///
457/// \param Param the parameter type
458///
459/// \param Arg the argument type
460///
461/// \param Info information about the template argument deduction itself
462///
463/// \param Deduced the deduced template arguments
464///
465/// \returns the result of template argument deduction so far. Note that a
466/// "success" result means that template argument deduction has not yet failed,
467/// but it may still fail, later, for other reasons.
468static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000469DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000470 TemplateParameterList *TemplateParams,
471 const TemplateSpecializationType *Param,
472 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000473 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000474 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000475 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000476
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000478 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000479 = dyn_cast<TemplateSpecializationType>(Arg)) {
480 // Perform template argument deduction for the template name.
481 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000482 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 Param->getTemplateName(),
484 SpecArg->getTemplateName(),
485 Info, Deduced))
486 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregore81f3e72009-07-07 23:09:34 +0000489 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000490 // argument. Ignore any missing/extra arguments, since they could be
491 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000492 return DeduceTemplateArguments(S, TemplateParams,
493 Param->template_arguments(),
494 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000495 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 // If the argument type is a class template specialization, we
499 // perform template argument deduction using its template
500 // arguments.
501 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000502 if (!RecordArg) {
503 Info.FirstArg = TemplateArgument(QualType(Param, 0));
504 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000505 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
508 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000509 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000510 if (!SpecArg) {
511 Info.FirstArg = TemplateArgument(QualType(Param, 0));
512 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000513 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Douglas Gregore81f3e72009-07-07 23:09:34 +0000516 // Perform template argument deduction for the template name.
517 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000518 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000519 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000520 Param->getTemplateName(),
521 TemplateName(SpecArg->getSpecializedTemplate()),
522 Info, Deduced))
523 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Douglas Gregor7baabef2010-12-22 18:17:10 +0000525 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000526 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
527 SpecArg->getTemplateArgs().asArray(), Info,
528 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000529}
530
John McCall08569062010-08-28 22:14:41 +0000531/// \brief Determines whether the given type is an opaque type that
532/// might be more qualified when instantiated.
533static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
534 switch (T->getTypeClass()) {
535 case Type::TypeOfExpr:
536 case Type::TypeOf:
537 case Type::DependentName:
538 case Type::Decltype:
539 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000540 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000541 return true;
542
543 case Type::ConstantArray:
544 case Type::IncompleteArray:
545 case Type::VariableArray:
546 case Type::DependentSizedArray:
547 return IsPossiblyOpaquelyQualifiedType(
548 cast<ArrayType>(T)->getElementType());
549
550 default:
551 return false;
552 }
553}
554
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000555/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000557getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
559 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000560
Douglas Gregor5499af42011-01-05 23:12:31 +0000561 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
562 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor5499af42011-01-05 23:12:31 +0000564 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
565 return std::make_pair(TTP->getDepth(), TTP->getIndex());
566}
567
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000568/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570getDepthAndIndex(UnexpandedParameterPack UPP) {
571 if (const TemplateTypeParmType *TTP
572 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
573 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000575 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
576}
577
Douglas Gregor5499af42011-01-05 23:12:31 +0000578/// \brief Helper function to build a TemplateParameter when we don't
579/// know its type statically.
580static TemplateParameter makeTemplateParameter(Decl *D) {
581 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
582 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000583 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000584 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000585
Douglas Gregor5499af42011-01-05 23:12:31 +0000586 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
587}
588
Richard Smith0a80d572014-05-29 01:12:14 +0000589/// A pack that we're currently deducing.
590struct clang::DeducedPack {
591 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000592
Richard Smith0a80d572014-05-29 01:12:14 +0000593 // The index of the pack.
594 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Richard Smith0a80d572014-05-29 01:12:14 +0000596 // The old value of the pack before we started deducing it.
597 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000598
Richard Smith0a80d572014-05-29 01:12:14 +0000599 // A deferred value of this pack from an inner deduction, that couldn't be
600 // deduced because this deduction hadn't happened yet.
601 DeducedTemplateArgument DeferredDeduction;
602
603 // The new value of the pack.
604 SmallVector<DeducedTemplateArgument, 4> New;
605
606 // The outer deduction for this pack, if any.
607 DeducedPack *Outer;
608};
609
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000610namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000611/// A scope in which we're performing pack deduction.
612class PackDeductionScope {
613public:
614 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
615 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
616 TemplateDeductionInfo &Info, TemplateArgument Pattern)
617 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
618 // Compute the set of template parameter indices that correspond to
619 // parameter packs expanded by the pack expansion.
620 {
621 llvm::SmallBitVector SawIndices(TemplateParams->size());
622 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
623 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
624 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
625 unsigned Depth, Index;
626 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000627 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000628 SawIndices[Index] = true;
629
630 // Save the deduced template argument for the parameter pack expanded
631 // by this pack expansion, then clear out the deduction.
632 DeducedPack Pack(Index);
633 Pack.Saved = Deduced[Index];
634 Deduced[Index] = TemplateArgument();
635
636 Packs.push_back(Pack);
637 }
638 }
639 }
640 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
641
642 for (auto &Pack : Packs) {
643 if (Info.PendingDeducedPacks.size() > Pack.Index)
644 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
645 else
646 Info.PendingDeducedPacks.resize(Pack.Index + 1);
647 Info.PendingDeducedPacks[Pack.Index] = &Pack;
648
649 if (S.CurrentInstantiationScope) {
650 // If the template argument pack was explicitly specified, add that to
651 // the set of deduced arguments.
652 const TemplateArgument *ExplicitArgs;
653 unsigned NumExplicitArgs;
654 NamedDecl *PartiallySubstitutedPack =
655 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
656 &ExplicitArgs, &NumExplicitArgs);
657 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000658 getDepthAndIndex(PartiallySubstitutedPack) ==
659 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000660 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
661 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000662 }
663 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000664
Richard Smith0a80d572014-05-29 01:12:14 +0000665 ~PackDeductionScope() {
666 for (auto &Pack : Packs)
667 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Richard Smith0a80d572014-05-29 01:12:14 +0000670 /// Move to deducing the next element in each pack that is being deduced.
671 void nextPackElement() {
672 // Capture the deduced template arguments for each parameter pack expanded
673 // by this pack expansion, add them to the list of arguments we've deduced
674 // for that pack, then clear out the deduced argument.
675 for (auto &Pack : Packs) {
676 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
677 if (!DeducedArg.isNull()) {
678 Pack.New.push_back(DeducedArg);
679 DeducedArg = DeducedTemplateArgument();
680 }
681 }
682 }
683
684 /// \brief Finish template argument deduction for a set of argument packs,
685 /// producing the argument packs and checking for consistency with prior
686 /// deductions.
687 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
688 // Build argument packs for each of the parameter packs expanded by this
689 // pack expansion.
690 for (auto &Pack : Packs) {
691 // Put back the old value for this pack.
692 Deduced[Pack.Index] = Pack.Saved;
693
694 // Build or find a new value for this pack.
695 DeducedTemplateArgument NewPack;
696 if (HasAnyArguments && Pack.New.empty()) {
697 if (Pack.DeferredDeduction.isNull()) {
698 // We were not able to deduce anything for this parameter pack
699 // (because it only appeared in non-deduced contexts), so just
700 // restore the saved argument pack.
701 continue;
702 }
703
704 NewPack = Pack.DeferredDeduction;
705 Pack.DeferredDeduction = TemplateArgument();
706 } else if (Pack.New.empty()) {
707 // If we deduced an empty argument pack, create it now.
708 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
709 } else {
710 TemplateArgument *ArgumentPack =
711 new (S.Context) TemplateArgument[Pack.New.size()];
712 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
713 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000714 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000715 Pack.New[0].wasDeducedFromArrayBound());
716 }
717
718 // Pick where we're going to put the merged pack.
719 DeducedTemplateArgument *Loc;
720 if (Pack.Outer) {
721 if (Pack.Outer->DeferredDeduction.isNull()) {
722 // Defer checking this pack until we have a complete pack to compare
723 // it against.
724 Pack.Outer->DeferredDeduction = NewPack;
725 continue;
726 }
727 Loc = &Pack.Outer->DeferredDeduction;
728 } else {
729 Loc = &Deduced[Pack.Index];
730 }
731
732 // Check the new pack matches any previous value.
733 DeducedTemplateArgument OldPack = *Loc;
734 DeducedTemplateArgument Result =
735 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
736
737 // If we deferred a deduction of this pack, check that one now too.
738 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
739 OldPack = Result;
740 NewPack = Pack.DeferredDeduction;
741 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
742 }
743
744 if (Result.isNull()) {
745 Info.Param =
746 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
747 Info.FirstArg = OldPack;
748 Info.SecondArg = NewPack;
749 return Sema::TDK_Inconsistent;
750 }
751
752 *Loc = Result;
753 }
754
755 return Sema::TDK_Success;
756 }
757
758private:
759 Sema &S;
760 TemplateParameterList *TemplateParams;
761 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
762 TemplateDeductionInfo &Info;
763
764 SmallVector<DeducedPack, 2> Packs;
765};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000766} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000767
Douglas Gregor5499af42011-01-05 23:12:31 +0000768/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000769/// types to the list of argument types, as in the parameter-type-lists of
770/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000771///
772/// \param S The semantic analysis object within which we are deducing
773///
774/// \param TemplateParams The template parameters that we are deducing
775///
776/// \param Params The list of parameter types
777///
778/// \param NumParams The number of types in \c Params
779///
780/// \param Args The list of argument types
781///
782/// \param NumArgs The number of types in \c Args
783///
784/// \param Info information about the template argument deduction itself
785///
786/// \param Deduced the deduced template arguments
787///
788/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
789/// how template argument deduction is performed.
790///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000791/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000793/// (C++0x [temp.deduct.partial]).
794///
Douglas Gregor5499af42011-01-05 23:12:31 +0000795/// \returns the result of template argument deduction so far. Note that a
796/// "success" result means that template argument deduction has not yet failed,
797/// but it may still fail, later, for other reasons.
798static Sema::TemplateDeductionResult
799DeduceTemplateArguments(Sema &S,
800 TemplateParameterList *TemplateParams,
801 const QualType *Params, unsigned NumParams,
802 const QualType *Args, unsigned NumArgs,
803 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000804 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000805 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000806 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000807 // Fast-path check to see if we have too many/too few arguments.
808 if (NumParams != NumArgs &&
809 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
810 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000811 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
Douglas Gregor5499af42011-01-05 23:12:31 +0000813 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814 // Similarly, if P has a form that contains (T), then each parameter type
815 // Pi of the respective parameter-type- list of P is compared with the
816 // corresponding parameter type Ai of the corresponding parameter-type-list
817 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000818 unsigned ArgIdx = 0, ParamIdx = 0;
819 for (; ParamIdx != NumParams; ++ParamIdx) {
820 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000822 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
823 if (!Expansion) {
824 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825
Douglas Gregor5499af42011-01-05 23:12:31 +0000826 // Make sure we have an argument.
827 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000828 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000829
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000830 if (isa<PackExpansionType>(Args[ArgIdx])) {
831 // C++0x [temp.deduct.type]p22:
832 // If the original function parameter associated with A is a function
833 // parameter pack and the function parameter associated with P is not
834 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000835 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor5499af42011-01-05 23:12:31 +0000838 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000839 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
840 Params[ParamIdx], Args[ArgIdx],
841 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000842 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor5499af42011-01-05 23:12:31 +0000845 ++ArgIdx;
846 continue;
847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000849 // C++0x [temp.deduct.type]p5:
850 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000852 // parameter-declaration-clause.
853 if (ParamIdx + 1 < NumParams)
854 return Sema::TDK_Success;
855
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000860 // comparison deduces template arguments for subsequent positions in the
861 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862
Douglas Gregor5499af42011-01-05 23:12:31 +0000863 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000864 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865
Douglas Gregor5499af42011-01-05 23:12:31 +0000866 bool HasAnyArguments = false;
867 for (; ArgIdx < NumArgs; ++ArgIdx) {
868 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869
Douglas Gregor5499af42011-01-05 23:12:31 +0000870 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000871 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000872 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
873 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000874 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Richard Smith0a80d572014-05-29 01:12:14 +0000877 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 // Build argument packs for each of the parameter packs expanded by this
881 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000882 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // Make sure we don't have any extra arguments.
887 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000888 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 return Sema::TDK_Success;
891}
892
Douglas Gregor1d684c22011-04-28 00:56:09 +0000893/// \brief Determine whether the parameter has qualifiers that are either
894/// inconsistent with or a superset of the argument's qualifiers.
895static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
896 QualType ArgType) {
897 Qualifiers ParamQs = ParamType.getQualifiers();
898 Qualifiers ArgQs = ArgType.getQualifiers();
899
900 if (ParamQs == ArgQs)
901 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000902
Douglas Gregor1d684c22011-04-28 00:56:09 +0000903 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000904 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000905 ParamQs.hasObjCGCAttr())
906 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000907
Douglas Gregor1d684c22011-04-28 00:56:09 +0000908 // Mismatched (but not missing) address spaces.
909 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
910 ParamQs.hasAddressSpace())
911 return true;
912
John McCall31168b02011-06-15 23:02:42 +0000913 // Mismatched (but not missing) Objective-C lifetime qualifiers.
914 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
915 ParamQs.hasObjCLifetime())
916 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000917
Douglas Gregor1d684c22011-04-28 00:56:09 +0000918 // CVR qualifier superset.
919 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
920 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
921 == ParamQs.getCVRQualifiers());
922}
923
Douglas Gregor19a41f12013-04-17 08:45:07 +0000924/// \brief Compare types for equality with respect to possibly compatible
925/// function types (noreturn adjustment, implicit calling conventions). If any
926/// of parameter and argument is not a function, just perform type comparison.
927///
928/// \param Param the template parameter type.
929///
930/// \param Arg the argument type.
931bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
932 CanQualType Arg) {
933 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
934 *ArgFunction = Arg->getAs<FunctionType>();
935
936 // Just compare if not functions.
937 if (!ParamFunction || !ArgFunction)
938 return Param == Arg;
939
Richard Smith3c4f8d22016-10-16 17:54:23 +0000940 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000941 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000942 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000943 return Arg == Context.getCanonicalType(AdjustedParam);
944
945 // FIXME: Compatible calling conventions.
946
947 return Param == Arg;
948}
949
Douglas Gregorcceb9752009-06-26 18:27:22 +0000950/// \brief Deduce the template arguments by comparing the parameter type and
951/// the argument type (C++ [temp.deduct.type]).
952///
Chandler Carruthc1263112010-02-07 21:33:28 +0000953/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000954///
955/// \param TemplateParams the template parameters that we are deducing
956///
957/// \param ParamIn the parameter type
958///
959/// \param ArgIn the argument type
960///
961/// \param Info information about the template argument deduction itself
962///
963/// \param Deduced the deduced template arguments
964///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000965/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000966/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000967///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000968/// \param PartialOrdering Whether we're performing template argument deduction
969/// in the context of partial ordering (C++0x [temp.deduct.partial]).
970///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000971/// \returns the result of template argument deduction so far. Note that a
972/// "success" result means that template argument deduction has not yet failed,
973/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000974static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000975DeduceTemplateArgumentsByTypeMatch(Sema &S,
976 TemplateParameterList *TemplateParams,
977 QualType ParamIn, QualType ArgIn,
978 TemplateDeductionInfo &Info,
979 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
980 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000981 bool PartialOrdering,
982 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000983 // We only want to look at the canonical types, since typedefs and
984 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000985 QualType Param = S.Context.getCanonicalType(ParamIn);
986 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000987
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000988 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000990 if (const PackExpansionType *ArgExpansion
991 = dyn_cast<PackExpansionType>(Arg))
992 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993
Douglas Gregorb837ea42011-01-11 17:34:58 +0000994 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000995 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996 // Before the partial ordering is done, certain transformations are
997 // performed on the types used for partial ordering:
998 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000999 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1000 if (ParamRef)
1001 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002
Douglas Gregorb837ea42011-01-11 17:34:58 +00001003 // - If A is a reference type, A is replaced by the type referred to.
1004 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1005 if (ArgRef)
1006 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Richard Smithed563c22015-02-20 04:45:22 +00001008 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1009 // C++11 [temp.deduct.partial]p9:
1010 // If, for a given type, deduction succeeds in both directions (i.e.,
1011 // the types are identical after the transformations above) and both
1012 // P and A were reference types [...]:
1013 // - if [one type] was an lvalue reference and [the other type] was
1014 // not, [the other type] is not considered to be at least as
1015 // specialized as [the first type]
1016 // - if [one type] is more cv-qualified than [the other type],
1017 // [the other type] is not considered to be at least as specialized
1018 // as [the first type]
1019 // Objective-C ARC adds:
1020 // - [one type] has non-trivial lifetime, [the other type] has
1021 // __unsafe_unretained lifetime, and the types are otherwise
1022 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001023 //
Richard Smithed563c22015-02-20 04:45:22 +00001024 // A is "considered to be at least as specialized" as P iff deduction
1025 // succeeds, so we model this as a deduction failure. Note that
1026 // [the first type] is P and [the other type] is A here; the standard
1027 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001028 Qualifiers ParamQuals = Param.getQualifiers();
1029 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001030 if ((ParamRef->isLValueReferenceType() &&
1031 !ArgRef->isLValueReferenceType()) ||
1032 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1033 (ParamQuals.hasNonTrivialObjCLifetime() &&
1034 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1035 ParamQuals.withoutObjCLifetime() ==
1036 ArgQuals.withoutObjCLifetime())) {
1037 Info.FirstArg = TemplateArgument(ParamIn);
1038 Info.SecondArg = TemplateArgument(ArgIn);
1039 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001040 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001042
Richard Smithed563c22015-02-20 04:45:22 +00001043 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 // version of P.
1047 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001049 // version of A.
1050 Arg = Arg.getUnqualifiedType();
1051 } else {
1052 // C++0x [temp.deduct.call]p4 bullet 1:
1053 // - If the original P is a reference type, the deduced A (i.e., the type
1054 // referred to by the reference) can be more cv-qualified than the
1055 // transformed A.
1056 if (TDF & TDF_ParamWithReferenceType) {
1057 Qualifiers Quals;
1058 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1059 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001060 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001061 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Douglas Gregor85f240c2011-01-25 17:19:08 +00001064 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1065 // C++0x [temp.deduct.type]p10:
1066 // If P and A are function types that originated from deduction when
1067 // taking the address of a function template (14.8.2.2) or when deducing
1068 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069 // Ai are parameters of the top-level parameter-type-list of P and A,
1070 // respectively, Pi is adjusted if it is an rvalue reference to a
1071 // cv-unqualified template parameter and Ai is an lvalue reference, in
1072 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001073 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1074 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001075 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001076 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001077
Douglas Gregor85f240c2011-01-25 17:19:08 +00001078 if (const RValueReferenceType *ParamRef
1079 = Param->getAs<RValueReferenceType>()) {
1080 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1081 !ParamRef->getPointeeType().getQualifiers())
1082 if (Arg->isLValueReferenceType())
1083 Param = ParamRef->getPointeeType();
1084 }
1085 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001088 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001089 // A template type argument T, a template template argument TT or a
1090 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001091 // the following forms:
1092 //
1093 // T
1094 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001095 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001096 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001097 // Just skip any attempts to deduce from a placeholder type or a parameter
1098 // at a different depth.
1099 if (Arg->isPlaceholderType() ||
1100 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001101 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001102
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001103 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001104 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001105
Douglas Gregor60454822009-07-22 20:02:25 +00001106 // If the argument type is an array type, move the qualifiers up to the
1107 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001108 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001109 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001110 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001111 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001112 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001113 RecanonicalizeArg = true;
1114 }
1115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001117 // The argument type can not be less qualified than the parameter
1118 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001119 if (!(TDF & TDF_IgnoreQualifiers) &&
1120 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001121 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001122 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001123 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001124 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001125 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001126
Richard Smith87d263e2016-12-25 08:05:23 +00001127 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1128 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001129 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001130 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001131
Douglas Gregor1d684c22011-04-28 00:56:09 +00001132 // Remove any qualifiers on the parameter from the deduced type.
1133 // We checked the qualifiers for consistency above.
1134 Qualifiers DeducedQs = DeducedType.getQualifiers();
1135 Qualifiers ParamQs = Param.getQualifiers();
1136 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1137 if (ParamQs.hasObjCGCAttr())
1138 DeducedQs.removeObjCGCAttr();
1139 if (ParamQs.hasAddressSpace())
1140 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001141 if (ParamQs.hasObjCLifetime())
1142 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001143
Douglas Gregore46db902011-06-17 22:11:49 +00001144 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001145 // If template deduction would produce a lifetime qualifier on a type
1146 // that is not a lifetime type, template argument deduction fails.
1147 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1148 !DeducedType->isDependentType()) {
1149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1150 Info.FirstArg = TemplateArgument(Param);
1151 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001152 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001153 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001154
Douglas Gregora4f2b432011-07-26 14:53:44 +00001155 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001156 // If template deduction would produce an argument type with lifetime type
1157 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001159 DeducedType->isObjCLifetimeType() &&
1160 !DeducedQs.hasObjCLifetime())
1161 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001162
Douglas Gregor1d684c22011-04-28 00:56:09 +00001163 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1164 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001165
Douglas Gregord6605db2009-07-22 21:30:48 +00001166 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001167 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Richard Smith5f274382016-09-28 23:55:27 +00001169 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001171 Deduced[Index],
1172 NewDeduced);
1173 if (Result.isNull()) {
1174 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1175 Info.FirstArg = Deduced[Index];
1176 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001180 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001182 }
1183
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001184 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001185 Info.FirstArg = TemplateArgument(ParamIn);
1186 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001187
Douglas Gregorfb322d82011-01-14 05:11:40 +00001188 // If the parameter is an already-substituted template parameter
1189 // pack, do nothing: we don't know which of its arguments to look
1190 // at, so we have to wait until all of the parameter packs in this
1191 // expansion have arguments.
1192 if (isa<SubstTemplateTypeParmPackType>(Param))
1193 return Sema::TDK_Success;
1194
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001195 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001196 CanQualType CanParam = S.Context.getCanonicalType(Param);
1197 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001198 if (!(TDF & TDF_IgnoreQualifiers)) {
1199 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001200 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001201 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001202 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001204 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001205 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001206
Douglas Gregor194ea692012-03-11 03:29:50 +00001207 // If the parameter type is not dependent, there is nothing to deduce.
1208 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001209 if (!(TDF & TDF_SkipNonDependent)) {
1210 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1211 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1212 Param != Arg;
1213 if (NonDeduced) {
1214 return Sema::TDK_NonDeducedMismatch;
1215 }
1216 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001217 return Sema::TDK_Success;
1218 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001219 } else if (!Param->isDependentType()) {
1220 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1221 ArgUnqualType = CanArg.getUnqualifiedType();
1222 bool Success = (TDF & TDF_InOverloadResolution)?
1223 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1224 ArgUnqualType) :
1225 ParamUnqualType == ArgUnqualType;
1226 if (Success)
1227 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001228 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001229
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001230 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 // Non-canonical types cannot appear here.
1232#define NON_CANONICAL_TYPE(Class, Base) \
1233 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1234#define TYPE(Class, Base)
1235#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001236
Douglas Gregor39c02722011-06-15 16:02:29 +00001237 case Type::TemplateTypeParm:
1238 case Type::SubstTemplateTypeParmPack:
1239 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001240
1241 // These types cannot be dependent, so simply check whether the types are
1242 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001243 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001244 case Type::VariableArray:
1245 case Type::Vector:
1246 case Type::FunctionNoProto:
1247 case Type::Record:
1248 case Type::Enum:
1249 case Type::ObjCObject:
1250 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001251 case Type::ObjCObjectPointer: {
1252 if (TDF & TDF_SkipNonDependent)
1253 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001254
Douglas Gregor194ea692012-03-11 03:29:50 +00001255 if (TDF & TDF_IgnoreQualifiers) {
1256 Param = Param.getUnqualifiedType();
1257 Arg = Arg.getUnqualifiedType();
1258 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001259
Douglas Gregor194ea692012-03-11 03:29:50 +00001260 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1261 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001262
1263 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001264 case Type::Complex:
1265 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001266 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1267 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001268 ComplexArg->getElementType(),
1269 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001270
1271 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001272
1273 // _Atomic T [extension]
1274 case Type::Atomic:
1275 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001276 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001277 cast<AtomicType>(Param)->getValueType(),
1278 AtomicArg->getValueType(),
1279 Info, Deduced, TDF);
1280
1281 return Sema::TDK_NonDeducedMismatch;
1282
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001283 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001284 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001285 QualType PointeeType;
1286 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1287 PointeeType = PointerArg->getPointeeType();
1288 } else if (const ObjCObjectPointerType *PointerArg
1289 = Arg->getAs<ObjCObjectPointerType>()) {
1290 PointeeType = PointerArg->getPointeeType();
1291 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001292 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Douglas Gregorfc516c92009-06-26 23:27:24 +00001295 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1297 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001298 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001299 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001302 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001303 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001304 const LValueReferenceType *ReferenceArg =
1305 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001306 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001307 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001309 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001310 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001311 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001313
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001314 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001315 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001316 const RValueReferenceType *ReferenceArg =
1317 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001318 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001319 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1322 cast<RValueReferenceType>(Param)->getPointeeType(),
1323 ReferenceArg->getPointeeType(),
1324 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001328 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001329 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001330 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001331 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001332 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCallf7332682010-08-19 00:20:19 +00001334 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001335 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1336 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1337 IncompleteArrayArg->getElementType(),
1338 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001339 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001340
1341 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001342 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001343 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001344 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001345 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001349 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001350 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001351 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCallf7332682010-08-19 00:20:19 +00001353 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1355 ConstantArrayParm->getElementType(),
1356 ConstantArrayArg->getElementType(),
1357 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 }
1359
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 // type [i]
1361 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001362 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001364 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001365
John McCallf7332682010-08-19 00:20:19 +00001366 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1367
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001368 // Check the element type of the arrays
1369 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001370 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001371 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001372 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1373 DependentArrayParm->getElementType(),
1374 ArrayArg->getElementType(),
1375 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001376 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001378 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001379 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001380 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001381 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001382 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001385 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001386 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1387 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001388 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001389 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1390 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001391 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001392 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001393 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001394 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001395 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 if (const DependentSizedArrayType *DependentArrayArg
1397 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001398 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001399 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001400 DependentArrayArg->getSizeExpr(),
1401 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001403 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001404 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
1407 // type(*)(T)
1408 // T(*)()
1409 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001410 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001411 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001412 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 dyn_cast<FunctionProtoType>(Arg);
1414 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001415 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001416
1417 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001418 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001419
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001421 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001423 != FunctionProtoArg->getRefQualifier() ||
1424 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001425 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001426
Anders Carlsson2128ec72009-06-08 15:19:08 +00001427 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001428 if (Sema::TemplateDeductionResult Result =
1429 DeduceTemplateArgumentsByTypeMatch(
1430 S, TemplateParams, FunctionProtoParam->getReturnType(),
1431 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001432 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Alp Toker9cacbab2014-01-20 20:26:09 +00001434 return DeduceTemplateArguments(
1435 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1436 FunctionProtoParam->getNumParams(),
1437 FunctionProtoArg->param_type_begin(),
1438 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCalle78aac42010-03-10 03:28:59 +00001441 case Type::InjectedClassName: {
1442 // Treat a template's injected-class-name as if the template
1443 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001444 Param = cast<InjectedClassNameType>(Param)
1445 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001446 assert(isa<TemplateSpecializationType>(Param) &&
1447 "injected class name is not a template specialization type");
1448 // fall through
1449 }
1450
Douglas Gregor705c9002009-06-26 20:57:09 +00001451 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001452 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001453 // TT<T>
1454 // TT<i>
1455 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001456 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001457 const TemplateSpecializationType *SpecParam =
1458 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Richard Smith9b296e32016-04-25 19:09:05 +00001460 // When Arg cannot be a derived class, we can just try to deduce template
1461 // arguments from the template-id.
1462 const RecordType *RecordT = Arg->getAs<RecordType>();
1463 if (!(TDF & TDF_DerivedClass) || !RecordT)
1464 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1465 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001466
Richard Smith9b296e32016-04-25 19:09:05 +00001467 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1468 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001469
Richard Smith9b296e32016-04-25 19:09:05 +00001470 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1471 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Richard Smith9b296e32016-04-25 19:09:05 +00001473 if (Result == Sema::TDK_Success)
1474 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Richard Smith9b296e32016-04-25 19:09:05 +00001476 // We cannot inspect base classes as part of deduction when the type
1477 // is incomplete, so either instantiate any templates necessary to
1478 // complete the type, or skip over it if it cannot be completed.
1479 if (!S.isCompleteType(Info.getLocation(), Arg))
1480 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001481
Richard Smith9b296e32016-04-25 19:09:05 +00001482 // C++14 [temp.deduct.call] p4b3:
1483 // If P is a class and P has the form simple-template-id, then the
1484 // transformed A can be a derived class of the deduced A. Likewise if
1485 // P is a pointer to a class of the form simple-template-id, the
1486 // transformed A can be a pointer to a derived class pointed to by the
1487 // deduced A.
1488 //
1489 // These alternatives are considered only if type deduction would
1490 // otherwise fail. If they yield more than one possible deduced A, the
1491 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001492
Faisal Vali683b0742016-05-19 02:28:21 +00001493 // Reset the incorrectly deduced argument from above.
1494 Deduced = DeducedOrig;
1495
1496 // Use data recursion to crawl through the list of base classes.
1497 // Visited contains the set of nodes we have already visited, while
1498 // ToVisit is our stack of records that we still need to visit.
1499 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1500 SmallVector<const RecordType *, 8> ToVisit;
1501 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001502 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001503 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001504 while (!ToVisit.empty()) {
1505 // Retrieve the next class in the inheritance hierarchy.
1506 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001507
Faisal Vali683b0742016-05-19 02:28:21 +00001508 // If we have already seen this type, skip it.
1509 if (!Visited.insert(NextT).second)
1510 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001511
Faisal Vali683b0742016-05-19 02:28:21 +00001512 // If this is a base class, try to perform template argument
1513 // deduction from it.
1514 if (NextT != RecordT) {
1515 TemplateDeductionInfo BaseInfo(Info.getLocation());
1516 Sema::TemplateDeductionResult BaseResult =
1517 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1518 QualType(NextT, 0), BaseInfo, Deduced);
1519
1520 // If template argument deduction for this base was successful,
1521 // note that we had some success. Otherwise, ignore any deductions
1522 // from this base class.
1523 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001524 // If we've already seen some success, then deduction fails due to
1525 // an ambiguity (temp.deduct.call p5).
1526 if (Successful)
1527 return Sema::TDK_MiscellaneousDeductionFailure;
1528
Faisal Vali683b0742016-05-19 02:28:21 +00001529 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001530 std::swap(SuccessfulDeduced, Deduced);
1531
Faisal Vali683b0742016-05-19 02:28:21 +00001532 Info.Param = BaseInfo.Param;
1533 Info.FirstArg = BaseInfo.FirstArg;
1534 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001535 }
1536
1537 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Faisal Vali683b0742016-05-19 02:28:21 +00001540 // Visit base classes
1541 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1542 for (const auto &Base : Next->bases()) {
1543 assert(Base.getType()->isRecordType() &&
1544 "Base class that isn't a record?");
1545 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1546 }
1547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001549 if (Successful) {
1550 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001551 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001552 }
Richard Smith9b296e32016-04-25 19:09:05 +00001553
Douglas Gregore81f3e72009-07-07 23:09:34 +00001554 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001555 }
1556
Douglas Gregor637d9982009-06-10 23:47:09 +00001557 // T type::*
1558 // T T::*
1559 // T (type::*)()
1560 // type (T::*)()
1561 // type (type::*)(T)
1562 // type (T::*)(T)
1563 // T (type::*)(T)
1564 // T (T::*)()
1565 // T (T::*)(T)
1566 case Type::MemberPointer: {
1567 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1568 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1569 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001570 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001571
David Majnemera381cda2015-11-30 20:34:28 +00001572 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1573 if (ParamPointeeType->isFunctionType())
1574 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1575 /*IsCtorOrDtor=*/false, Info.getLocation());
1576 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1577 if (ArgPointeeType->isFunctionType())
1578 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1579 /*IsCtorOrDtor=*/false, Info.getLocation());
1580
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001581 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001582 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001583 ParamPointeeType,
1584 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001585 Info, Deduced,
1586 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001587 return Result;
1588
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001589 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1590 QualType(MemPtrParam->getClass(), 0),
1591 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001592 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001593 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001594 }
1595
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001596 // (clang extension)
1597 //
Mike Stump11289f42009-09-09 15:08:12 +00001598 // type(^)(T)
1599 // T(^)()
1600 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001601 case Type::BlockPointer: {
1602 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1603 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Anders Carlssona767eee2009-06-12 16:23:10 +00001605 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001606 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001607
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001608 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1609 BlockPtrParam->getPointeeType(),
1610 BlockPtrArg->getPointeeType(),
1611 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001612 }
1613
Douglas Gregor39c02722011-06-15 16:02:29 +00001614 // (clang extension)
1615 //
1616 // T __attribute__(((ext_vector_type(<integral constant>))))
1617 case Type::ExtVector: {
1618 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1619 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1620 // Make sure that the vectors have the same number of elements.
1621 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1622 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001623
Douglas Gregor39c02722011-06-15 16:02:29 +00001624 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001625 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626 VectorParam->getElementType(),
1627 VectorArg->getElementType(),
1628 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001629 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001630
1631 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001632 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1633 // We can't check the number of elements, since the argument has a
1634 // dependent number of elements. This can only occur during partial
1635 // ordering.
1636
1637 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001638 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1639 VectorParam->getElementType(),
1640 VectorArg->getElementType(),
1641 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001642 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001643
Douglas Gregor39c02722011-06-15 16:02:29 +00001644 return Sema::TDK_NonDeducedMismatch;
1645 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001646
Douglas Gregor39c02722011-06-15 16:02:29 +00001647 // (clang extension)
1648 //
1649 // T __attribute__(((ext_vector_type(N))))
1650 case Type::DependentSizedExtVector: {
1651 const DependentSizedExtVectorType *VectorParam
1652 = cast<DependentSizedExtVectorType>(Param);
1653
1654 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1655 // Perform deduction on the element types.
1656 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001657 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1658 VectorParam->getElementType(),
1659 VectorArg->getElementType(),
1660 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001661 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001662
Douglas Gregor39c02722011-06-15 16:02:29 +00001663 // Perform deduction on the vector size, if we can.
1664 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001665 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001666 if (!NTTP)
1667 return Sema::TDK_Success;
1668
1669 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1670 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001671 // Note that we use the "array bound" rules here; just like in that
1672 // case, we don't have any particular type for the vector size, but
1673 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001674 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001675 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001676 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001677 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001678
1679 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001680 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1681 // Perform deduction on the element types.
1682 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001683 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1684 VectorParam->getElementType(),
1685 VectorArg->getElementType(),
1686 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001687 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001688
Douglas Gregor39c02722011-06-15 16:02:29 +00001689 // Perform deduction on the vector size, if we can.
1690 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001691 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001692 if (!NTTP)
1693 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001694
Richard Smith5f274382016-09-28 23:55:27 +00001695 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1696 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001697 Info, Deduced);
1698 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001699
Douglas Gregor39c02722011-06-15 16:02:29 +00001700 return Sema::TDK_NonDeducedMismatch;
1701 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001702
Douglas Gregor637d9982009-06-10 23:47:09 +00001703 case Type::TypeOfExpr:
1704 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001705 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001706 case Type::UnresolvedUsing:
1707 case Type::Decltype:
1708 case Type::UnaryTransform:
1709 case Type::Auto:
1710 case Type::DependentTemplateSpecialization:
1711 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001712 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001713 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001714 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001715 }
1716
David Blaikiee4d798f2012-01-20 21:50:17 +00001717 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001718}
1719
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001720static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001721DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001722 TemplateParameterList *TemplateParams,
1723 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001724 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001725 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001726 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001727 // If the template argument is a pack expansion, perform template argument
1728 // deduction against the pattern of that expansion. This only occurs during
1729 // partial ordering.
1730 if (Arg.isPackExpansion())
1731 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001732
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001733 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001734 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001735 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001736
1737 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001738 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001739 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1740 Param.getAsType(),
1741 Arg.getAsType(),
1742 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001743 Info.FirstArg = Param;
1744 Info.SecondArg = Arg;
1745 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001746
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001747 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001748 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001749 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001750 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001751 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001752 Info.FirstArg = Param;
1753 Info.SecondArg = Arg;
1754 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001755
1756 case TemplateArgument::TemplateExpansion:
1757 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001759 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001760 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001761 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001762 return Sema::TDK_Success;
1763
1764 Info.FirstArg = Param;
1765 Info.SecondArg = Arg;
1766 return Sema::TDK_NonDeducedMismatch;
1767
1768 case TemplateArgument::NullPtr:
1769 if (Arg.getKind() == TemplateArgument::NullPtr &&
1770 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001771 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001773 Info.FirstArg = Param;
1774 Info.SecondArg = Arg;
1775 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001776
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001777 case TemplateArgument::Integral:
1778 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001779 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001780 return Sema::TDK_Success;
1781
1782 Info.FirstArg = Param;
1783 Info.SecondArg = Arg;
1784 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001785 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001786
1787 if (Arg.getKind() == TemplateArgument::Expression) {
1788 Info.FirstArg = Param;
1789 Info.SecondArg = Arg;
1790 return Sema::TDK_NonDeducedMismatch;
1791 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001792
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001793 Info.FirstArg = Param;
1794 Info.SecondArg = Arg;
1795 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001796
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001797 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001798 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001799 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001800 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001801 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001802 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001803 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001804 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001805 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001806 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001807 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1808 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001809 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001810 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001811 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1812 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001813 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001814 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1815 Arg.getAsDecl(),
1816 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001817 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001819 Info.FirstArg = Param;
1820 Info.SecondArg = Arg;
1821 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001822 }
Mike Stump11289f42009-09-09 15:08:12 +00001823
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001824 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001825 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001826 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001827 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001828 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
David Blaikiee4d798f2012-01-20 21:50:17 +00001831 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001832}
1833
Douglas Gregor7baabef2010-12-22 18:17:10 +00001834/// \brief Determine whether there is a template argument to be used for
1835/// deduction.
1836///
1837/// This routine "expands" argument packs in-place, overriding its input
1838/// parameters so that \c Args[ArgIdx] will be the available template argument.
1839///
1840/// \returns true if there is another template argument (which will be at
1841/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001842static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1843 unsigned &ArgIdx) {
1844 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001845 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregor7baabef2010-12-22 18:17:10 +00001847 const TemplateArgument &Arg = Args[ArgIdx];
1848 if (Arg.getKind() != TemplateArgument::Pack)
1849 return true;
1850
Richard Smith0bda5b52016-12-23 23:46:56 +00001851 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1852 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001853 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001854 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001855}
1856
Douglas Gregord0ad2942010-12-23 01:24:45 +00001857/// \brief Determine whether the given set of template arguments has a pack
1858/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001859static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1860 bool FoundPackExpansion = false;
1861 for (const auto &A : Args) {
1862 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001863 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001864
1865 if (A.getKind() == TemplateArgument::Pack)
1866 return hasPackExpansionBeforeEnd(A.pack_elements());
1867
1868 if (A.isPackExpansion())
1869 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001871
Douglas Gregord0ad2942010-12-23 01:24:45 +00001872 return false;
1873}
1874
Douglas Gregor7baabef2010-12-22 18:17:10 +00001875static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001876DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001877 ArrayRef<TemplateArgument> Params,
1878 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001879 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001880 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1881 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001882 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883 // If the template argument list of P contains a pack expansion that is not
1884 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001885 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001886 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001887 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001889 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890 // If P has a form that contains <T> or <i>, then each argument Pi of the
1891 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001892 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001893 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001894 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001896 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Douglas Gregor7baabef2010-12-22 18:17:10 +00001898 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001899 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001900 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1901 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001902
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001903 if (Args[ArgIdx].isPackExpansion()) {
1904 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1905 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001906 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001909 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001910 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001911 = DeduceTemplateArguments(S, TemplateParams,
1912 Params[ParamIdx], Args[ArgIdx],
1913 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 return Result;
1915
Douglas Gregor7baabef2010-12-22 18:17:10 +00001916 // Move to the next argument.
1917 ++ArgIdx;
1918 continue;
1919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001921 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001923 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924 // If Pi is a pack expansion, then the pattern of Pi is compared with
1925 // each remaining argument in the template argument list of A. Each
1926 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // template parameter packs expanded by Pi.
1928 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001929
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001930 // FIXME: If there are no remaining arguments, we can bail out early
1931 // and set any deduced parameter packs to an empty argument pack.
1932 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933
Richard Smith0a80d572014-05-29 01:12:14 +00001934 // Prepare to deduce the packs within the pattern.
1935 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001936
1937 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001939 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001940 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001941 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001942 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001944 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001946 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1947 Info, Deduced))
1948 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Richard Smith0a80d572014-05-29 01:12:14 +00001950 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001953 // Build argument packs for each of the parameter packs expanded by this
1954 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001955 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor7baabef2010-12-22 18:17:10 +00001959 return Sema::TDK_Success;
1960}
1961
Mike Stump11289f42009-09-09 15:08:12 +00001962static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001963DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001964 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001965 const TemplateArgumentList &ParamList,
1966 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001967 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001968 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001969 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
1970 ArgList.asArray(), Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001971}
1972
Douglas Gregor705c9002009-06-26 20:57:09 +00001973/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001974static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001975 const TemplateArgument &X,
1976 const TemplateArgument &Y) {
1977 if (X.getKind() != Y.getKind())
1978 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor705c9002009-06-26 20:57:09 +00001980 switch (X.getKind()) {
1981 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001982 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregor705c9002009-06-26 20:57:09 +00001984 case TemplateArgument::Type:
1985 return Context.getCanonicalType(X.getAsType()) ==
1986 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor705c9002009-06-26 20:57:09 +00001988 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001989 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001990
1991 case TemplateArgument::NullPtr:
1992 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001994 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001995 case TemplateArgument::TemplateExpansion:
1996 return Context.getCanonicalTemplateName(
1997 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1998 Context.getCanonicalTemplateName(
1999 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregor705c9002009-06-26 20:57:09 +00002001 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002002 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002004 case TemplateArgument::Expression: {
2005 llvm::FoldingSetNodeID XID, YID;
2006 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002008 return XID == YID;
2009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Douglas Gregor705c9002009-06-26 20:57:09 +00002011 case TemplateArgument::Pack:
2012 if (X.pack_size() != Y.pack_size())
2013 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002014
2015 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2016 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002017 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002018 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002019 if (!isSameTemplateArg(Context, *XP, *YP))
2020 return false;
2021
2022 return true;
2023 }
2024
David Blaikiee4d798f2012-01-20 21:50:17 +00002025 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002026}
2027
Douglas Gregorca4686d2011-01-04 23:35:54 +00002028/// \brief Allocate a TemplateArgumentLoc where all locations have
2029/// been initialized to the given location.
2030///
James Dennett634962f2012-06-14 21:40:34 +00002031/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002032/// location information for.
2033///
2034/// \param NTTPType For a declaration template argument, the type of
2035/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002036/// argument. Can be null if no type sugar is available to add to the
2037/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002038///
2039/// \param Loc The source location to use for the resulting template
2040/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002041TemplateArgumentLoc
2042Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2043 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002044 switch (Arg.getKind()) {
2045 case TemplateArgument::Null:
2046 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregorca4686d2011-01-04 23:35:54 +00002048 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002049 return TemplateArgumentLoc(
2050 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002053 if (NTTPType.isNull())
2054 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002055 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2056 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002057 return TemplateArgumentLoc(TemplateArgument(E), E);
2058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059
Eli Friedmanb826a002012-09-26 02:36:12 +00002060 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002061 if (NTTPType.isNull())
2062 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002063 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2064 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002065 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2066 E);
2067 }
2068
Douglas Gregorca4686d2011-01-04 23:35:54 +00002069 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002070 Expr *E =
2071 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002072 return TemplateArgumentLoc(TemplateArgument(E), E);
2073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregor9d802122011-03-02 17:09:35 +00002075 case TemplateArgument::Template:
2076 case TemplateArgument::TemplateExpansion: {
2077 NestedNameSpecifierLocBuilder Builder;
2078 TemplateName Template = Arg.getAsTemplate();
2079 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002080 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002081 else if (QualifiedTemplateName *QTN =
2082 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002083 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002084
Douglas Gregor9d802122011-03-02 17:09:35 +00002085 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002086 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002087 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002088
2089 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002090 Loc, Loc);
2091 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002092
Douglas Gregorca4686d2011-01-04 23:35:54 +00002093 case TemplateArgument::Expression:
2094 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096 case TemplateArgument::Pack:
2097 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099
David Blaikiee4d798f2012-01-20 21:50:17 +00002100 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002101}
2102
2103
2104/// \brief Convert the given deduced template argument and add it to the set of
2105/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002106static bool
2107ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2108 DeducedTemplateArgument Arg,
2109 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002110 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002111 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002112 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002113 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2114 unsigned ArgumentPackIndex) {
2115 // Convert the deduced template argument into a template
2116 // argument that we can check, almost as if the user had written
2117 // the template argument explicitly.
2118 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002119 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002120
2121 // Check the template argument, converting it as necessary.
2122 return S.CheckTemplateArgument(
2123 Param, ArgLoc, Template, Template->getLocation(),
2124 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002125 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002126 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2127 : Sema::CTAK_Deduced)
2128 : Sema::CTAK_Specified);
2129 };
2130
Douglas Gregorca4686d2011-01-04 23:35:54 +00002131 if (Arg.getKind() == TemplateArgument::Pack) {
2132 // This is a template argument pack, so check each of its arguments against
2133 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002134 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002135 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002136 // When converting the deduced template argument, append it to the
2137 // general output list. We need to do this so that the template argument
2138 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002139 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002140 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002141 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2142 "deduced nested pack");
2143 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002144 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145
Douglas Gregor51bc5712011-01-05 20:52:18 +00002146 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002147 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149
Richard Smithdf18ee92016-02-03 20:40:30 +00002150 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002151 // itself, in case that substitution fails.
2152 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002153 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002154 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002155 MultiLevelTemplateArgumentList Args(TemplateArgs);
2156
2157 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2158 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2159 NTTP, Output,
2160 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002161 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002162 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2163 NTTP->getDeclName()).isNull())
2164 return true;
2165 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2166 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2167 TTP, Output,
2168 Template->getSourceRange());
2169 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2170 return true;
2171 }
2172 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002173 }
Richard Smith37acb792016-02-03 20:15:01 +00002174
Douglas Gregorca4686d2011-01-04 23:35:54 +00002175 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002176 Output.push_back(
2177 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002178 return false;
2179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
Richard Smith37acb792016-02-03 20:15:01 +00002181 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002182}
2183
Richard Smith1f5be4d2016-12-21 01:10:31 +00002184// FIXME: This should not be a template, but
2185// ClassTemplatePartialSpecializationDecl sadly does not derive from
2186// TemplateDecl.
2187template<typename TemplateDeclT>
2188static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002189 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002190 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2191 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2192 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2193 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2194 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2195
2196 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2197 NamedDecl *Param = TemplateParams->getParam(I);
2198
2199 if (!Deduced[I].isNull()) {
2200 if (I < NumAlreadyConverted) {
2201 // We have already fully type-checked and converted this
2202 // argument, because it was explicitly-specified. Just record the
2203 // presence of this argument.
2204 Builder.push_back(Deduced[I]);
2205 // We may have had explicitly-specified template arguments for a
2206 // template parameter pack (that may or may not have been extended
2207 // via additional deduced arguments).
2208 if (Param->isParameterPack() && CurrentInstantiationScope) {
2209 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2210 Param) {
2211 // Forget the partially-substituted pack; its substitution is now
2212 // complete.
2213 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2214 }
2215 }
2216 continue;
2217 }
2218
2219 // We have deduced this argument, so it still needs to be
2220 // checked and converted.
2221 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002222 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002223 Info.Param = makeTemplateParameter(Param);
2224 // FIXME: These template arguments are temporary. Free them!
2225 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2226 return Sema::TDK_SubstitutionFailure;
2227 }
2228
2229 continue;
2230 }
2231
2232 // C++0x [temp.arg.explicit]p3:
2233 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2234 // be deduced to an empty sequence of template arguments.
2235 // FIXME: Where did the word "trailing" come from?
2236 if (Param->isTemplateParameterPack()) {
2237 // We may have had explicitly-specified template arguments for this
2238 // template parameter pack. If so, our empty deduction extends the
2239 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2240 const TemplateArgument *ExplicitArgs;
2241 unsigned NumExplicitArgs;
2242 if (CurrentInstantiationScope &&
2243 CurrentInstantiationScope->getPartiallySubstitutedPack(
2244 &ExplicitArgs, &NumExplicitArgs) == Param) {
2245 Builder.push_back(TemplateArgument(
2246 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2247
2248 // Forget the partially-substituted pack; its substitution is now
2249 // complete.
2250 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2251 } else {
2252 // Go through the motions of checking the empty argument pack against
2253 // the parameter pack.
2254 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002255 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2256 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002257 Info.Param = makeTemplateParameter(Param);
2258 // FIXME: These template arguments are temporary. Free them!
2259 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2260 return Sema::TDK_SubstitutionFailure;
2261 }
2262 }
2263 continue;
2264 }
2265
2266 // Substitute into the default template argument, if available.
2267 bool HasDefaultArg = false;
2268 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2269 if (!TD) {
2270 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2271 return Sema::TDK_Incomplete;
2272 }
2273
2274 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2275 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2276 HasDefaultArg);
2277
2278 // If there was no default argument, deduction is incomplete.
2279 if (DefArg.getArgument().isNull()) {
2280 Info.Param = makeTemplateParameter(
2281 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2282 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2283 if (PartialOverloading) break;
2284
2285 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2286 : Sema::TDK_Incomplete;
2287 }
2288
2289 // Check whether we can actually use the default argument.
2290 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2291 TD->getSourceRange().getEnd(), 0, Builder,
2292 Sema::CTAK_Specified)) {
2293 Info.Param = makeTemplateParameter(
2294 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2295 // FIXME: These template arguments are temporary. Free them!
2296 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2297 return Sema::TDK_SubstitutionFailure;
2298 }
2299
2300 // If we get here, we successfully used the default template argument.
2301 }
2302
2303 return Sema::TDK_Success;
2304}
2305
Richard Smith0da6dc42016-12-24 16:40:51 +00002306DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2307 if (auto *DC = dyn_cast<DeclContext>(D))
2308 return DC;
2309 return D->getDeclContext();
2310}
2311
2312template<typename T> struct IsPartialSpecialization {
2313 static constexpr bool value = false;
2314};
2315template<>
2316struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2317 static constexpr bool value = true;
2318};
2319template<>
2320struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2321 static constexpr bool value = true;
2322};
2323
2324/// Complete template argument deduction for a partial specialization.
2325template <typename T>
2326static typename std::enable_if<IsPartialSpecialization<T>::value,
2327 Sema::TemplateDeductionResult>::type
2328FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002329 Sema &S, T *Partial, bool IsPartialOrdering,
2330 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002331 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2332 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002333 // Unevaluated SFINAE context.
2334 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002335 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002336
Richard Smith0da6dc42016-12-24 16:40:51 +00002337 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002338
2339 // C++ [temp.deduct.type]p2:
2340 // [...] or if any template argument remains neither deduced nor
2341 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002342 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002343 if (auto Result = ConvertDeducedTemplateArguments(
2344 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002345 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002346
Douglas Gregor684268d2010-04-29 06:21:43 +00002347 // Form the template argument list from the deduced template arguments.
2348 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002349 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002350
Douglas Gregor684268d2010-04-29 06:21:43 +00002351 Info.reset(DeducedArgumentList);
2352
2353 // Substitute the deduced template arguments into the template
2354 // arguments of the class template partial specialization, and
2355 // verify that the instantiated template arguments are both valid
2356 // and are equivalent to the template arguments originally provided
2357 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002358 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002359 auto *Template = Partial->getSpecializedTemplate();
2360 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2361 Partial->getTemplateArgsAsWritten();
2362 const TemplateArgumentLoc *PartialTemplateArgs =
2363 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002364
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002365 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2366 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002367
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002368 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002369 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2370 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2371 if (ParamIdx >= Partial->getTemplateParameters()->size())
2372 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2373
Richard Smith0da6dc42016-12-24 16:40:51 +00002374 Decl *Param = const_cast<NamedDecl *>(
2375 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002376 Info.Param = makeTemplateParameter(Param);
2377 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2378 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002379 }
2380
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002381 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002382 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2383 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002384 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002385
Richard Smith0da6dc42016-12-24 16:40:51 +00002386 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002387 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002388 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002389 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002390 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002391 Info.FirstArg = TemplateArgs[I];
2392 Info.SecondArg = InstArg;
2393 return Sema::TDK_NonDeducedMismatch;
2394 }
2395 }
2396
2397 if (Trap.hasErrorOccurred())
2398 return Sema::TDK_SubstitutionFailure;
2399
2400 return Sema::TDK_Success;
2401}
2402
Douglas Gregor170bc422009-06-12 22:31:52 +00002403/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002404/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002405/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002406Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002407Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002408 const TemplateArgumentList &TemplateArgs,
2409 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002410 if (Partial->isInvalidDecl())
2411 return TDK_Invalid;
2412
Douglas Gregor170bc422009-06-12 22:31:52 +00002413 // C++ [temp.class.spec.match]p2:
2414 // A partial specialization matches a given actual template
2415 // argument list if the template arguments of the partial
2416 // specialization can be deduced from the actual template argument
2417 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002418
2419 // Unevaluated SFINAE context.
2420 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002421 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002422
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002423 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002424 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002425 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002426 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002427 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002428 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002429 TemplateArgs, Info, Deduced))
2430 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002431
Richard Smith80934652012-07-16 01:09:10 +00002432 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002433 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2434 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002435 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002436 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002437
Douglas Gregore1416332009-06-14 08:02:22 +00002438 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002439 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002440
Richard Smith87d263e2016-12-25 08:05:23 +00002441 return ::FinishTemplateArgumentDeduction(
2442 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002443}
Douglas Gregor91772d12009-06-13 00:26:55 +00002444
Larisse Voufo39a1e502013-08-06 01:03:05 +00002445/// \brief Perform template argument deduction to determine whether
2446/// the given template arguments match the given variable template
2447/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002448Sema::TemplateDeductionResult
2449Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2450 const TemplateArgumentList &TemplateArgs,
2451 TemplateDeductionInfo &Info) {
2452 if (Partial->isInvalidDecl())
2453 return TDK_Invalid;
2454
2455 // C++ [temp.class.spec.match]p2:
2456 // A partial specialization matches a given actual template
2457 // argument list if the template arguments of the partial
2458 // specialization can be deduced from the actual template argument
2459 // list (14.8.2).
2460
2461 // Unevaluated SFINAE context.
2462 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2463 SFINAETrap Trap(*this);
2464
2465 SmallVector<DeducedTemplateArgument, 4> Deduced;
2466 Deduced.resize(Partial->getTemplateParameters()->size());
2467 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2468 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2469 TemplateArgs, Info, Deduced))
2470 return Result;
2471
2472 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002473 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2474 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002475 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002476 return TDK_InstantiationDepth;
2477
2478 if (Trap.hasErrorOccurred())
2479 return Sema::TDK_SubstitutionFailure;
2480
Richard Smith87d263e2016-12-25 08:05:23 +00002481 return ::FinishTemplateArgumentDeduction(
2482 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002483}
2484
Douglas Gregorfc516c92009-06-26 23:27:24 +00002485/// \brief Determine whether the given type T is a simple-template-id type.
2486static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002487 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002488 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002489 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Douglas Gregorfc516c92009-06-26 23:27:24 +00002491 return false;
2492}
Douglas Gregor9b146582009-07-08 20:55:45 +00002493
2494/// \brief Substitute the explicitly-provided template arguments into the
2495/// given function template according to C++ [temp.arg.explicit].
2496///
2497/// \param FunctionTemplate the function template into which the explicit
2498/// template arguments will be substituted.
2499///
James Dennett634962f2012-06-14 21:40:34 +00002500/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002501/// arguments.
2502///
Mike Stump11289f42009-09-09 15:08:12 +00002503/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002504/// with the converted and checked explicit template arguments.
2505///
Mike Stump11289f42009-09-09 15:08:12 +00002506/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002507/// parameters.
2508///
2509/// \param FunctionType if non-NULL, the result type of the function template
2510/// will also be instantiated and the pointed-to value will be updated with
2511/// the instantiated function type.
2512///
2513/// \param Info if substitution fails for any reason, this object will be
2514/// populated with more information about the failure.
2515///
2516/// \returns TDK_Success if substitution was successful, or some failure
2517/// condition.
2518Sema::TemplateDeductionResult
2519Sema::SubstituteExplicitTemplateArguments(
2520 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002521 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002522 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2523 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002524 QualType *FunctionType,
2525 TemplateDeductionInfo &Info) {
2526 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2527 TemplateParameterList *TemplateParams
2528 = FunctionTemplate->getTemplateParameters();
2529
John McCall6b51f282009-11-23 01:53:49 +00002530 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002531 // No arguments to substitute; just copy over the parameter types and
2532 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002533 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002534 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002535
Douglas Gregor9b146582009-07-08 20:55:45 +00002536 if (FunctionType)
2537 *FunctionType = Function->getType();
2538 return TDK_Success;
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Eli Friedman77dcc722012-02-08 03:07:05 +00002541 // Unevaluated SFINAE context.
2542 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002543 SFINAETrap Trap(*this);
2544
Douglas Gregor9b146582009-07-08 20:55:45 +00002545 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002546 // Template arguments that are present shall be specified in the
2547 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002548 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002549 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002550 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002551
2552 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002553 // explicitly-specified template arguments against this function template,
2554 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002555 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002556 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2557 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002558 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2559 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002560 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002561 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregor9b146582009-07-08 20:55:45 +00002563 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002564 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002565 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002566 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002567 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002568 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002569 if (Index >= TemplateParams->size())
2570 Index = TemplateParams->size() - 1;
2571 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002572 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregor9b146582009-07-08 20:55:45 +00002575 // Form the template argument list from the explicitly-specified
2576 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002577 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002578 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002579 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580
John McCall036855a2010-10-12 19:40:14 +00002581 // Template argument deduction and the final substitution should be
2582 // done in the context of the templated declaration. Explicit
2583 // argument substitution, on the other hand, needs to happen in the
2584 // calling context.
2585 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2586
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002588 // note that the template argument pack is partially substituted and record
2589 // the explicit template arguments. They'll be used as part of deduction
2590 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002591 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2592 const TemplateArgument &Arg = Builder[I];
2593 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002594 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002596 Arg.pack_begin(),
2597 Arg.pack_size());
2598 break;
2599 }
2600 }
2601
Richard Smith5e580292012-02-10 09:58:53 +00002602 const FunctionProtoType *Proto
2603 = Function->getType()->getAs<FunctionProtoType>();
2604 assert(Proto && "Function template does not have a prototype?");
2605
Richard Smith70b13042015-01-09 01:19:56 +00002606 // Isolate our substituted parameters from our caller.
2607 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2608
John McCallc8e321d2016-03-01 02:09:25 +00002609 ExtParameterInfoBuilder ExtParamInfos;
2610
Douglas Gregor9b146582009-07-08 20:55:45 +00002611 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002612 // explicitly-specified template arguments. If the function has a trailing
2613 // return type, substitute it after the arguments to ensure we substitute
2614 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002615 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002616 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002617 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002618 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002619 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002620 return TDK_SubstitutionFailure;
2621 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002622
Richard Smith5e580292012-02-10 09:58:53 +00002623 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002624 QualType ResultType;
2625 {
2626 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002627 // If a declaration declares a member function or member function
2628 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002629 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002630 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002631 // declarator.
2632 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002633 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002634 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2635 ThisContext = Method->getParent();
2636 ThisTypeQuals = Method->getTypeQualifiers();
2637 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002638
Douglas Gregor3024f072012-04-16 07:05:22 +00002639 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002640 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002641
2642 ResultType =
2643 SubstType(Proto->getReturnType(),
2644 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2645 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002646 if (ResultType.isNull() || Trap.hasErrorOccurred())
2647 return TDK_SubstitutionFailure;
2648 }
John McCallc8e321d2016-03-01 02:09:25 +00002649
Richard Smith5e580292012-02-10 09:58:53 +00002650 // Instantiate the types of each of the function parameters given the
2651 // explicitly-specified template arguments if we didn't do so earlier.
2652 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002653 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002654 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002655 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002656 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002657 return TDK_SubstitutionFailure;
2658
Douglas Gregor9b146582009-07-08 20:55:45 +00002659 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002660 auto EPI = Proto->getExtProtoInfo();
2661 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002662 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002663 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002664 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002665 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002666 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2667 return TDK_SubstitutionFailure;
2668 }
Mike Stump11289f42009-09-09 15:08:12 +00002669
Douglas Gregor9b146582009-07-08 20:55:45 +00002670 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002671 // Trailing template arguments that can be deduced (14.8.2) may be
2672 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002673 // template arguments can be deduced, they may all be omitted; in this
2674 // case, the empty template argument list <> itself may also be omitted.
2675 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002676 // Take all of the explicitly-specified arguments and put them into
2677 // the set of deduced template arguments. Explicitly-specified
2678 // parameter packs, however, will be set to NULL since the deduction
2679 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002680 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002681 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2682 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2683 if (Arg.getKind() == TemplateArgument::Pack)
2684 Deduced.push_back(DeducedTemplateArgument());
2685 else
2686 Deduced.push_back(Arg);
2687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor9b146582009-07-08 20:55:45 +00002689 return TDK_Success;
2690}
2691
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002692/// \brief Check whether the deduced argument type for a call to a function
2693/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002694static bool
2695CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002696 QualType DeducedA) {
2697 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002698
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002699 QualType A = OriginalArg.OriginalArgType;
2700 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002701
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002702 // Check for type equality (top-level cv-qualifiers are ignored).
2703 if (Context.hasSameUnqualifiedType(A, DeducedA))
2704 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002705
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002706 // Strip off references on the argument types; they aren't needed for
2707 // the following checks.
2708 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2709 DeducedA = DeducedARef->getPointeeType();
2710 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2711 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002712
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002713 // C++ [temp.deduct.call]p4:
2714 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002715 // - If the original P is a reference type, the deduced A (i.e., the
2716 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002717 // the transformed A.
2718 if (const ReferenceType *OriginalParamRef
2719 = OriginalParamType->getAs<ReferenceType>()) {
2720 // We don't want to keep the reference around any more.
2721 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002722
Richard Smith1be59c52016-10-22 01:32:19 +00002723 // FIXME: Resolve core issue (no number yet): if the original P is a
2724 // reference type and the transformed A is function type "noexcept F",
2725 // the deduced A can be F.
2726 QualType Tmp;
2727 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2728 return false;
2729
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002730 Qualifiers AQuals = A.getQualifiers();
2731 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002732
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002733 // Under Objective-C++ ARC, the deduced type may have implicitly
2734 // been given strong or (when dealing with a const reference)
2735 // unsafe_unretained lifetime. If so, update the original
2736 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002737 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002738 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2739 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2740 (DeducedAQuals.hasConst() &&
2741 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2742 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002743 }
2744
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002745 if (AQuals == DeducedAQuals) {
2746 // Qualifiers match; there's nothing to do.
2747 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002748 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002749 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002750 // Qualifiers are compatible, so have the argument type adopt the
2751 // deduced argument type's qualifiers as if we had performed the
2752 // qualification conversion.
2753 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2754 }
2755 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002756
2757 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002758 // type that can be converted to the deduced A via a function pointer
2759 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002760 //
Richard Smith1be59c52016-10-22 01:32:19 +00002761 // Also allow conversions which merely strip __attribute__((noreturn)) from
2762 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002763 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002764 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002765 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002766 (S.IsQualificationConversion(A, DeducedA, false,
2767 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002768 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002769 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002770
Simon Pilgrim728134c2016-08-12 11:43:57 +00002771 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002772 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002773 // [...] Likewise, if P is a pointer to a class of the form
2774 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002775 // derived class pointed to by the deduced A.
2776 if (const PointerType *OriginalParamPtr
2777 = OriginalParamType->getAs<PointerType>()) {
2778 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2779 if (const PointerType *APtr = A->getAs<PointerType>()) {
2780 if (A->getPointeeType()->isRecordType()) {
2781 OriginalParamType = OriginalParamPtr->getPointeeType();
2782 DeducedA = DeducedAPtr->getPointeeType();
2783 A = APtr->getPointeeType();
2784 }
2785 }
2786 }
2787 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002788
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002789 if (Context.hasSameUnqualifiedType(A, DeducedA))
2790 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002791
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002792 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002793 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002794 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002795
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002796 return true;
2797}
2798
Mike Stump11289f42009-09-09 15:08:12 +00002799/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002800/// checking the deduced template arguments for completeness and forming
2801/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002802///
2803/// \param OriginalCallArgs If non-NULL, the original call arguments against
2804/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002805Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002806Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002807 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002808 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002809 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002810 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002811 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2812 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002813 // Unevaluated SFINAE context.
2814 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002815 SFINAETrap Trap(*this);
2816
Douglas Gregor9b146582009-07-08 20:55:45 +00002817 // Enter a new template instantiation context while we instantiate the
2818 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002819 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002820 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2821 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002822 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2823 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002824 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002825 return TDK_InstantiationDepth;
2826
John McCalle23b8712010-04-29 01:18:58 +00002827 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002828
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002829 // C++ [temp.deduct.type]p2:
2830 // [...] or if any template argument remains neither deduced nor
2831 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002832 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002833 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002834 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002835 CurrentInstantiationScope, NumExplicitlySpecified,
2836 PartialOverloading))
2837 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002838
2839 // Form the template argument list from the deduced template arguments.
2840 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002841 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002842 Info.reset(DeducedArgumentList);
2843
Mike Stump11289f42009-09-09 15:08:12 +00002844 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002845 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002846 DeclContext *Owner = FunctionTemplate->getDeclContext();
2847 if (FunctionTemplate->getFriendObjectKind())
2848 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002849 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002850 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002851 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002852 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002853 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002854
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002856 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857
Mike Stump11289f42009-09-09 15:08:12 +00002858 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002859 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002860 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2861 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002862 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002863
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002864 // There may have been an error that did not prevent us from constructing a
2865 // declaration. Mark the declaration invalid and return with a substitution
2866 // failure.
2867 if (Trap.hasErrorOccurred()) {
2868 Specialization->setInvalidDecl(true);
2869 return TDK_SubstitutionFailure;
2870 }
2871
Douglas Gregore65aacb2011-06-16 16:50:48 +00002872 if (OriginalCallArgs) {
2873 // C++ [temp.deduct.call]p4:
2874 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002875 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002876 // is transformed as described above). [...]
2877 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2878 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002879 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002880
Douglas Gregore65aacb2011-06-16 16:50:48 +00002881 if (ParamIdx >= Specialization->getNumParams())
2882 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002883
Douglas Gregore65aacb2011-06-16 16:50:48 +00002884 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002885 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2886 Info.FirstArg = TemplateArgument(DeducedA);
2887 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2888 Info.CallArgIndex = OriginalArg.ArgIdx;
2889 return TDK_DeducedMismatch;
2890 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002891 }
2892 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002893
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002894 // If we suppressed any diagnostics while performing template argument
2895 // deduction, and if we haven't already instantiated this declaration,
2896 // keep track of these diagnostics. They'll be emitted if this specialization
2897 // is actually used.
2898 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002899 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002900 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2901 if (Pos == SuppressedDiagnostics.end())
2902 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2903 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002905
Mike Stump11289f42009-09-09 15:08:12 +00002906 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002907}
2908
John McCall8d08b9b2010-08-27 09:08:28 +00002909/// Gets the type of a function for template-argument-deducton
2910/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002911static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002912 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002913 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002914 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002915 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002916 return QualType();
2917
John McCallc1f69982010-02-02 02:21:27 +00002918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002919 if (Method->isInstance()) {
2920 // An instance method that's referenced in a form that doesn't
2921 // look like a member pointer is just invalid.
2922 if (!R.HasFormOfMemberPointer) return QualType();
2923
Richard Smith2a7d4812013-05-04 07:00:32 +00002924 return S.Context.getMemberPointerType(Fn->getType(),
2925 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002926 }
2927
2928 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002929 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002930}
2931
2932/// Apply the deduction rules for overload sets.
2933///
2934/// \return the null type if this argument should be treated as an
2935/// undeduced context
2936static QualType
2937ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002938 Expr *Arg, QualType ParamType,
2939 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940
John McCall8d08b9b2010-08-27 09:08:28 +00002941 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002942
John McCall8d08b9b2010-08-27 09:08:28 +00002943 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002944
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002945 // C++0x [temp.deduct.call]p4
2946 unsigned TDF = 0;
2947 if (ParamWasReference)
2948 TDF |= TDF_ParamWithReferenceType;
2949 if (R.IsAddressOfOperand)
2950 TDF |= TDF_IgnoreQualifiers;
2951
John McCallc1f69982010-02-02 02:21:27 +00002952 // C++0x [temp.deduct.call]p6:
2953 // When P is a function type, pointer to function type, or pointer
2954 // to member function type:
2955
2956 if (!ParamType->isFunctionType() &&
2957 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002958 !ParamType->isMemberFunctionPointerType()) {
2959 if (Ovl->hasExplicitTemplateArgs()) {
2960 // But we can still look for an explicit specialization.
2961 if (FunctionDecl *ExplicitSpec
2962 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00002963 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002964 }
John McCallc1f69982010-02-02 02:21:27 +00002965
George Burgess IVcc2f3552016-03-19 21:51:45 +00002966 DeclAccessPair DAP;
2967 if (FunctionDecl *Viable =
2968 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
2969 return GetTypeOfFunction(S, R, Viable);
2970
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002971 return QualType();
2972 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002973
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002974 // Gather the explicit template arguments, if any.
2975 TemplateArgumentListInfo ExplicitTemplateArgs;
2976 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00002977 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00002978 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00002979 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2980 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00002981 NamedDecl *D = (*I)->getUnderlyingDecl();
2982
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002983 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2984 // - If the argument is an overload set containing one or more
2985 // function templates, the parameter is treated as a
2986 // non-deduced context.
2987 if (!Ovl->hasExplicitTemplateArgs())
2988 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002989
2990 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00002991 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00002992 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002993 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
2994 Specialization, Info))
2995 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002996
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002997 D = Specialization;
2998 }
John McCallc1f69982010-02-02 02:21:27 +00002999
3000 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003001 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003002 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003003
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003004 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003006 ArgType->isFunctionType())
3007 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003008
John McCallc1f69982010-02-02 02:21:27 +00003009 // - If the argument is an overload set (not containing function
3010 // templates), trial argument deduction is attempted using each
3011 // of the members of the set. If deduction succeeds for only one
3012 // of the overload set members, that member is used as the
3013 // argument value for the deduction. If deduction succeeds for
3014 // more than one member of the overload set the parameter is
3015 // treated as a non-deduced context.
3016
3017 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3018 // Type deduction is done independently for each P/A pair, and
3019 // the deduced template argument values are then combined.
3020 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003021 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003022 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003023 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003024 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003025 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3026 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003027 if (Result) continue;
3028 if (!Match.isNull()) return QualType();
3029 Match = ArgType;
3030 }
3031
3032 return Match;
3033}
3034
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003035/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003036/// described in C++ [temp.deduct.call].
3037///
3038/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003039/// argument deduction based on this P/A pair because the argument is an
3040/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003041static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3042 TemplateParameterList *TemplateParams,
3043 QualType &ParamType,
3044 QualType &ArgType,
3045 Expr *Arg,
3046 unsigned &TDF) {
3047 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003048 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003049 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003050 if (ParamType.hasQualifiers())
3051 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003052
3053 // [...] If P is a reference type, the type referred to by P is
3054 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003055 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003056 if (ParamRefType)
3057 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003058
Nathan Sidwell96090022015-01-16 15:20:14 +00003059 // Overload sets usually make this parameter an undeduced context,
3060 // but there are sometimes special circumstances. Typically
3061 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003062 if (ArgType == S.Context.OverloadTy) {
3063 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3064 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003065 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003066 if (ArgType.isNull())
3067 return true;
3068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003069
Douglas Gregor7825bf32011-01-06 22:09:01 +00003070 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003071 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003072 if (ArgType->isIncompleteArrayType()) {
3073 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003074 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003075 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003076
Douglas Gregor7825bf32011-01-06 22:09:01 +00003077 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003078 // If P is an rvalue reference to a cv-unqualified template
3079 // parameter and the argument is an lvalue, the type "lvalue
3080 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003081 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003082 !ParamType.getQualifiers() &&
3083 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003084 Arg->isLValue())
3085 ArgType = S.Context.getLValueReferenceType(ArgType);
3086 } else {
3087 // C++ [temp.deduct.call]p2:
3088 // If P is not a reference type:
3089 // - If A is an array type, the pointer type produced by the
3090 // array-to-pointer standard conversion (4.2) is used in place of
3091 // A for type deduction; otherwise,
3092 if (ArgType->isArrayType())
3093 ArgType = S.Context.getArrayDecayedType(ArgType);
3094 // - If A is a function type, the pointer type produced by the
3095 // function-to-pointer standard conversion (4.3) is used in place
3096 // of A for type deduction; otherwise,
3097 else if (ArgType->isFunctionType())
3098 ArgType = S.Context.getPointerType(ArgType);
3099 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003100 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003101 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003102 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003103 }
3104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105
Douglas Gregor7825bf32011-01-06 22:09:01 +00003106 // C++0x [temp.deduct.call]p4:
3107 // In general, the deduction process attempts to find template argument
3108 // values that will make the deduced A identical to A (after the type A
3109 // is transformed as described above). [...]
3110 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111
Douglas Gregor7825bf32011-01-06 22:09:01 +00003112 // - If the original P is a reference type, the deduced A (i.e., the
3113 // type referred to by the reference) can be more cv-qualified than
3114 // the transformed A.
3115 if (ParamRefType)
3116 TDF |= TDF_ParamWithReferenceType;
3117 // - The transformed A can be another pointer or pointer to member
3118 // type that can be converted to the deduced A via a qualification
3119 // conversion (4.4).
3120 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3121 ArgType->isObjCObjectPointerType())
3122 TDF |= TDF_IgnoreQualifiers;
3123 // - If P is a class and P has the form simple-template-id, then the
3124 // transformed A can be a derived class of the deduced A. Likewise,
3125 // if P is a pointer to a class of the form simple-template-id, the
3126 // transformed A can be a pointer to a derived class pointed to by
3127 // the deduced A.
3128 if (isSimpleTemplateIdType(ParamType) ||
3129 (isa<PointerType>(ParamType) &&
3130 isSimpleTemplateIdType(
3131 ParamType->getAs<PointerType>()->getPointeeType())))
3132 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Douglas Gregor7825bf32011-01-06 22:09:01 +00003134 return false;
3135}
3136
Nico Weberc153d242014-07-28 00:02:09 +00003137static bool
3138hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3139 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003140
Hubert Tong3280b332015-06-25 00:25:49 +00003141static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3142 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3143 Expr *Arg, TemplateDeductionInfo &Info,
3144 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3145
3146/// \brief Attempt template argument deduction from an initializer list
3147/// deemed to be an argument in a function call.
3148static bool
3149DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3150 QualType AdjustedParamType, InitListExpr *ILE,
3151 TemplateDeductionInfo &Info,
3152 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3153 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003154
3155 // [temp.deduct.call] p1 (post CWG-1591)
3156 // If removing references and cv-qualifiers from P gives
3157 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3158 // non-empty initializer list (8.5.4), then deduction is performed instead for
3159 // each element of the initializer list, taking P0 as a function template
3160 // parameter type and the initializer element as its argument, and in the
3161 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3162 // length of the initializer list. Otherwise, an initializer list argument
3163 // causes the parameter to be considered a non-deduced context
3164
3165 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3166
3167 const bool IsDependentSizedArray =
3168 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3169
Faisal Validd76cc12015-12-10 12:29:11 +00003170 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003171
3172 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3173 S.isStdInitializerList(AdjustedParamType, &ElTy);
3174
3175 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003176 return false;
3177
3178 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003179 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3180 // deduce against the 'T' in T[N].
3181 if (ElTy.isNull()) {
3182 assert(!IsSTDList);
3183 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003184 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003185 // Deduction only needs to be done for dependent types.
3186 if (ElTy->isDependentType()) {
3187 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003188 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3189 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003190 return true;
3191 }
3192 }
3193 if (IsDependentSizedArray) {
3194 const DependentSizedArrayType *ArrTy =
3195 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3196 // Determine the array bound is something we can deduce.
3197 if (NonTypeTemplateParmDecl *NTTP =
Richard Smith87d263e2016-12-25 08:05:23 +00003198 getDeducedParameterFromExpr(Info, ArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003199 // We can perform template argument deduction for the given non-type
3200 // template parameter.
3201 assert(NTTP->getDepth() == 0 &&
3202 "Cannot deduce non-type template argument at depth > 0");
3203 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3204 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003205
Faisal Valif6dfdb32015-12-10 05:36:39 +00003206 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003207 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003208 /*ArrayBound=*/true, Info, Deduced);
3209 }
3210 }
Hubert Tong3280b332015-06-25 00:25:49 +00003211 return true;
3212}
3213
Sebastian Redl19181662012-03-15 21:40:51 +00003214/// \brief Perform template argument deduction by matching a parameter type
3215/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003216/// an initializer list that was originally matched against a parameter
3217/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003218static Sema::TemplateDeductionResult
3219DeduceTemplateArgumentByListElement(Sema &S,
3220 TemplateParameterList *TemplateParams,
3221 QualType ParamType, Expr *Arg,
3222 TemplateDeductionInfo &Info,
3223 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3224 unsigned TDF) {
3225 // Handle the case where an init list contains another init list as the
3226 // element.
3227 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003228 Sema::TemplateDeductionResult Result;
3229 if (!DeduceFromInitializerList(S, TemplateParams,
3230 ParamType.getNonReferenceType(), ILE, Info,
3231 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003232 return Sema::TDK_Success; // Just ignore this expression.
3233
Hubert Tong3280b332015-06-25 00:25:49 +00003234 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003235 }
3236
3237 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003238 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003239 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003240 ArgType, Arg, TDF)) {
3241 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003242 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003243 }
Sebastian Redl19181662012-03-15 21:40:51 +00003244 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003245 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003246}
3247
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003248/// \brief Perform template argument deduction from a function call
3249/// (C++ [temp.deduct.call]).
3250///
3251/// \param FunctionTemplate the function template for which we are performing
3252/// template argument deduction.
3253///
James Dennett18348b62012-06-22 08:52:37 +00003254/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003255/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003256///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003257/// \param Args the function call arguments
3258///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003259/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003260/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003261/// template argument deduction.
3262///
3263/// \param Info the argument will be updated to provide additional information
3264/// about template argument deduction.
3265///
3266/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003267Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3268 FunctionTemplateDecl *FunctionTemplate,
3269 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003270 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3271 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003272 if (FunctionTemplate->isInvalidDecl())
3273 return TDK_Invalid;
3274
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003275 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003276 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003277
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003278 // C++ [temp.deduct.call]p1:
3279 // Template argument deduction is done by comparing each function template
3280 // parameter type (call it P) with the type of the corresponding argument
3281 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003282 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003283 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003284 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003285 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003286 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003287 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003288 if (Proto->isTemplateVariadic())
3289 /* Do nothing */;
3290 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003291 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003292 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003293 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Douglas Gregor89026b52009-06-30 23:57:56 +00003296 // The types of the parameters from which we will perform template argument
3297 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003298 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003299 TemplateParameterList *TemplateParams
3300 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003301 SmallVector<DeducedTemplateArgument, 4> Deduced;
3302 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003303 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003304 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003305 TemplateDeductionResult Result =
3306 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003307 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003308 Deduced,
3309 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003310 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003311 Info);
3312 if (Result)
3313 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003314
3315 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003316 } else {
3317 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003318 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003319 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Douglas Gregor89026b52009-06-30 23:57:56 +00003322 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003323 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003324 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003325 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003326 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3327 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003328 QualType OrigParamType = ParamTypes[ParamIdx];
3329 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003330
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003332 = dyn_cast<PackExpansionType>(ParamType);
3333 if (!ParamExpansion) {
3334 // Simple case: matching a function parameter to a function argument.
3335 if (ArgIdx >= CheckArgs)
3336 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337
Douglas Gregor7825bf32011-01-06 22:09:01 +00003338 Expr *Arg = Args[ArgIdx++];
3339 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003340
Douglas Gregor7825bf32011-01-06 22:09:01 +00003341 unsigned TDF = 0;
3342 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3343 ParamType, ArgType, Arg,
3344 TDF))
3345 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
Douglas Gregor0c83c812011-10-09 22:06:46 +00003347 // If we have nothing to deduce, we're done.
3348 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3349 continue;
3350
Sebastian Redl43144e72012-01-17 22:49:58 +00003351 // If the argument is an initializer list ...
3352 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003353 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003354 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003355 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3356 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003357 continue;
3358
Hubert Tong3280b332015-06-25 00:25:49 +00003359 if (Result)
3360 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003361 // Don't track the argument type, since an initializer list has none.
3362 continue;
3363 }
3364
Douglas Gregore65aacb2011-06-16 16:50:48 +00003365 // Keep track of the argument type and corresponding parameter index,
3366 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003367 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003368 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003369
Douglas Gregor7825bf32011-01-06 22:09:01 +00003370 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003371 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3372 ParamType, ArgType,
3373 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003374 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003375
Douglas Gregor7825bf32011-01-06 22:09:01 +00003376 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378
Douglas Gregor7825bf32011-01-06 22:09:01 +00003379 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380 // For a function parameter pack that occurs at the end of the
3381 // parameter-declaration-list, the type A of each remaining argument of
3382 // the call is compared with the type P of the declarator-id of the
3383 // function parameter pack. Each comparison deduces template arguments
3384 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003385 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003387 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003388 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor7825bf32011-01-06 22:09:01 +00003391 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003392 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3393 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
Douglas Gregor7825bf32011-01-06 22:09:01 +00003395 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003396 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003397 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Douglas Gregore65aacb2011-06-16 16:50:48 +00003399 QualType OrigParamType = ParamPattern;
3400 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003401 Expr *Arg = Args[ArgIdx];
3402 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003403
Douglas Gregor7825bf32011-01-06 22:09:01 +00003404 unsigned TDF = 0;
3405 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3406 ParamType, ArgType, Arg,
3407 TDF)) {
3408 // We can't actually perform any deduction for this argument, so stop
3409 // deduction at this point.
3410 ++ArgIdx;
3411 break;
3412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Sebastian Redl43144e72012-01-17 22:49:58 +00003414 // As above, initializer lists need special handling.
3415 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003416 TemplateDeductionResult Result;
3417 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3418 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003419 ++ArgIdx;
3420 break;
3421 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003422
Hubert Tong3280b332015-06-25 00:25:49 +00003423 if (Result)
3424 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003425 } else {
3426
3427 // Keep track of the argument type and corresponding argument index,
3428 // so we can check for compatibility between the deduced A and A.
3429 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003430 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003431 ArgType));
3432
3433 if (TemplateDeductionResult Result
3434 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3435 ParamType, ArgType, Info,
3436 Deduced, TDF))
3437 return Result;
3438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
Richard Smith0a80d572014-05-29 01:12:14 +00003440 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Douglas Gregor7825bf32011-01-06 22:09:01 +00003443 // Build argument packs for each of the parameter packs expanded by this
3444 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003445 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003447
Douglas Gregor7825bf32011-01-06 22:09:01 +00003448 // After we've matching against a parameter pack, we're done.
3449 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003450 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003451
Mike Stump11289f42009-09-09 15:08:12 +00003452 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003453 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003454 Info, &OriginalCallArgs,
3455 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003456}
3457
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003458QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003459 QualType FunctionType,
3460 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003461 if (ArgFunctionType.isNull())
3462 return ArgFunctionType;
3463
3464 const FunctionProtoType *FunctionTypeP =
3465 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003466 const FunctionProtoType *ArgFunctionTypeP =
3467 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003468
3469 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3470 bool Rebuild = false;
3471
3472 CallingConv CC = FunctionTypeP->getCallConv();
3473 if (EPI.ExtInfo.getCC() != CC) {
3474 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3475 Rebuild = true;
3476 }
3477
3478 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3479 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3480 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3481 Rebuild = true;
3482 }
3483
3484 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3485 ArgFunctionTypeP->hasExceptionSpec())) {
3486 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3487 Rebuild = true;
3488 }
3489
3490 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003491 return ArgFunctionType;
3492
Richard Smithbaa47832016-12-01 02:11:49 +00003493 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3494 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003495}
3496
Douglas Gregor9b146582009-07-08 20:55:45 +00003497/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003498/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3499/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003500///
3501/// \param FunctionTemplate the function template for which we are performing
3502/// template argument deduction.
3503///
James Dennett18348b62012-06-22 08:52:37 +00003504/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003505/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003506///
3507/// \param ArgFunctionType the function type that will be used as the
3508/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003509/// function template's function type. This type may be NULL, if there is no
3510/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003511///
3512/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003513/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003514/// template argument deduction.
3515///
3516/// \param Info the argument will be updated to provide additional information
3517/// about template argument deduction.
3518///
Richard Smithbaa47832016-12-01 02:11:49 +00003519/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3520/// the address of a function template per [temp.deduct.funcaddr] and
3521/// [over.over]. If \c false, we are looking up a function template
3522/// specialization based on its signature, per [temp.deduct.decl].
3523///
Douglas Gregor9b146582009-07-08 20:55:45 +00003524/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003525Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3526 FunctionTemplateDecl *FunctionTemplate,
3527 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3528 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3529 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003530 if (FunctionTemplate->isInvalidDecl())
3531 return TDK_Invalid;
3532
Douglas Gregor9b146582009-07-08 20:55:45 +00003533 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3534 TemplateParameterList *TemplateParams
3535 = FunctionTemplate->getTemplateParameters();
3536 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003537
3538 // When taking the address of a function, we require convertibility of
3539 // the resulting function type. Otherwise, we allow arbitrary mismatches
3540 // of calling convention, noreturn, and noexcept.
3541 if (!IsAddressOfFunction)
3542 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3543 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003544
Douglas Gregor9b146582009-07-08 20:55:45 +00003545 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003546 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003547 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003548 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003549 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003550 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003551 if (TemplateDeductionResult Result
3552 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003553 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003554 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003555 &FunctionType, Info))
3556 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003557
3558 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003559 }
3560
Eli Friedman77dcc722012-02-08 03:07:05 +00003561 // Unevaluated SFINAE context.
3562 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003563 SFINAETrap Trap(*this);
3564
John McCallc1f69982010-02-02 02:21:27 +00003565 Deduced.resize(TemplateParams->size());
3566
Richard Smith2a7d4812013-05-04 07:00:32 +00003567 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003568 // type so that we treat it as a non-deduced context in what follows. If we
3569 // are looking up by signature, the signature type should also have a deduced
3570 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003571 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003572 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003573 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003574 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003575 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003576 }
3577
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003578 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003579 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003580 if (IsAddressOfFunction)
3581 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003582 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003583 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003584 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003585 FunctionType, ArgFunctionType,
3586 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003587 return Result;
3588 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003589
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003591 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3592 NumExplicitlySpecified,
3593 Specialization, Info))
3594 return Result;
3595
Richard Smith2a7d4812013-05-04 07:00:32 +00003596 // If the function has a deduced return type, deduce it now, so we can check
3597 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003598 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003599 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003600 DeduceReturnType(Specialization, Info.getLocation(), false))
3601 return TDK_MiscellaneousDeductionFailure;
3602
Richard Smith9095e5b2016-11-01 01:31:23 +00003603 // If the function has a dependent exception specification, resolve it now,
3604 // so we can check that the exception specification matches.
3605 auto *SpecializationFPT =
3606 Specialization->getType()->castAs<FunctionProtoType>();
3607 if (getLangOpts().CPlusPlus1z &&
3608 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3609 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3610 return TDK_MiscellaneousDeductionFailure;
3611
Richard Smithbaa47832016-12-01 02:11:49 +00003612 // Adjust the exception specification of the argument again to match the
3613 // substituted and resolved type we just formed. (Calling convention and
3614 // noreturn can't be dependent, so we don't actually need this for them
3615 // right now.)
3616 QualType SpecializationType = Specialization->getType();
3617 if (!IsAddressOfFunction)
3618 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3619 /*AdjustExceptionSpec*/true);
3620
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003621 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003622 // specialization with respect to arguments of compatible pointer to function
3623 // types, template argument deduction fails.
3624 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003625 if (IsAddressOfFunction &&
3626 !isSameOrCompatibleFunctionType(
3627 Context.getCanonicalType(SpecializationType),
3628 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003629 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003630
3631 if (!IsAddressOfFunction &&
3632 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003633 return TDK_MiscellaneousDeductionFailure;
3634 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003635
3636 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003637}
3638
Simon Pilgrim728134c2016-08-12 11:43:57 +00003639/// \brief Given a function declaration (e.g. a generic lambda conversion
3640/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003641/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3642/// to replace 'auto' with and not the actual result type you want
3643/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003644static inline void
3645SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003646 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003647 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003648 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003649 assert(AutoResultType->getContainedAutoType());
3650 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003651 TypeToReplaceAutoWith);
3652 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3653}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654
Simon Pilgrim728134c2016-08-12 11:43:57 +00003655/// \brief Given a specialized conversion operator of a generic lambda
3656/// create the corresponding specializations of the call operator and
3657/// the static-invoker. If the return type of the call operator is auto,
3658/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003659/// return type of the destination function ptr.
3660
Simon Pilgrim728134c2016-08-12 11:43:57 +00003661static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003662SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3663 CXXConversionDecl *ConversionSpecialized,
3664 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3665 QualType ReturnTypeOfDestFunctionPtr,
3666 TemplateDeductionInfo &TDInfo,
3667 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003668
Faisal Vali2b3a3012013-10-24 23:40:02 +00003669 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003670 assert(LambdaClass && LambdaClass->isGenericLambda());
3671
Faisal Vali2b3a3012013-10-24 23:40:02 +00003672 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003673 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003674 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003675 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003676
3677 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003678 CallOpGeneric->getDescribedFunctionTemplate();
3679
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003681 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003682 // generic lambda's call operator.
3683 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003684 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3685 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 0, CallOpSpecialized, TDInfo))
3687 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003688
Faisal Vali2b3a3012013-10-24 23:40:02 +00003689 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003690 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3691 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003692 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003693 CallOpSpecialized->getPointOfInstantiation(),
3694 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003695
Faisal Vali2b3a3012013-10-24 23:40:02 +00003696 // Check to see if the return type of the destination ptr-to-function
3697 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003698 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003699 ReturnTypeOfDestFunctionPtr))
3700 return Sema::TDK_NonDeducedMismatch;
3701 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003702 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003703 // specialized our corresponding call operator, we are ready to
3704 // specialize the static invoker with the deduced arguments of our
3705 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003706 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3708 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3709
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003710#ifndef NDEBUG
3711 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3712#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003713 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003715 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716 "If the call operator succeeded so should the invoker!");
3717 // Set the result type to match the corresponding call operator
3718 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003719 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3720 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003721 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003722 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003723 // to substitute into the 'auto' of the invoker and conversion
3724 // function.
3725 // For e.g.
3726 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3727 // We don't want to subst 'int*' into 'auto' to get int**.
3728
Alp Toker314cc812014-01-25 16:55:45 +00003729 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3730 ->getContainedAutoType()
3731 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003732 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3733 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003734 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 TypeToReplaceAutoWith, S);
3736 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003737
Faisal Vali2b3a3012013-10-24 23:40:02 +00003738 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003739 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003741 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003742 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3743 getType().getTypePtr()->castAs<FunctionProtoType>();
3744 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3745 EPI.TypeQuals = 0;
3746 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003747 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003748 return Sema::TDK_Success;
3749}
Douglas Gregor05155d82009-08-21 23:19:43 +00003750/// \brief Deduce template arguments for a templated conversion
3751/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3752/// conversion function template specialization.
3753Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003754Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003755 QualType ToType,
3756 CXXConversionDecl *&Specialization,
3757 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003758 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003759 return TDK_Invalid;
3760
Faisal Vali2b3a3012013-10-24 23:40:02 +00003761 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003762 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3763
Faisal Vali2b3a3012013-10-24 23:40:02 +00003764 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003765
3766 // Canonicalize the types for deduction.
3767 QualType P = Context.getCanonicalType(FromType);
3768 QualType A = Context.getCanonicalType(ToType);
3769
Douglas Gregord99609a2011-03-06 09:03:20 +00003770 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003771 // If P is a reference type, the type referred to by P is used for
3772 // type deduction.
3773 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3774 P = PRef->getPointeeType();
3775
Douglas Gregord99609a2011-03-06 09:03:20 +00003776 // C++0x [temp.deduct.conv]p4:
3777 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003778 // for type deduction.
3779 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003780 A = ARef->getPointeeType().getUnqualifiedType();
3781 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003782 //
Mike Stump11289f42009-09-09 15:08:12 +00003783 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003784 else {
3785 assert(!A->isReferenceType() && "Reference types were handled above");
3786
3787 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003788 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003789 // of P for type deduction; otherwise,
3790 if (P->isArrayType())
3791 P = Context.getArrayDecayedType(P);
3792 // - If P is a function type, the pointer type produced by the
3793 // function-to-pointer standard conversion (4.3) is used in
3794 // place of P for type deduction; otherwise,
3795 else if (P->isFunctionType())
3796 P = Context.getPointerType(P);
3797 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003798 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003799 else
3800 P = P.getUnqualifiedType();
3801
Douglas Gregord99609a2011-03-06 09:03:20 +00003802 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003803 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003804 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003805 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003806 A = A.getUnqualifiedType();
3807 }
3808
Eli Friedman77dcc722012-02-08 03:07:05 +00003809 // Unevaluated SFINAE context.
3810 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003811 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003812
3813 // C++ [temp.deduct.conv]p1:
3814 // Template argument deduction is done by comparing the return
3815 // type of the template conversion function (call it P) with the
3816 // type that is required as the result of the conversion (call it
3817 // A) as described in 14.8.2.4.
3818 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003819 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003820 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003821 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003822
3823 // C++0x [temp.deduct.conv]p4:
3824 // In general, the deduction process attempts to find template
3825 // argument values that will make the deduced A identical to
3826 // A. However, there are two cases that allow a difference:
3827 unsigned TDF = 0;
3828 // - If the original A is a reference type, A can be more
3829 // cv-qualified than the deduced A (i.e., the type referred to
3830 // by the reference)
3831 if (ToType->isReferenceType())
3832 TDF |= TDF_ParamWithReferenceType;
3833 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003834 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003835 // conversion.
3836 //
3837 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3838 // both P and A are pointers or member pointers. In this case, we
3839 // just ignore cv-qualifiers completely).
3840 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003841 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 TDF |= TDF_IgnoreQualifiers;
3843 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003844 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3845 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003846 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003847
3848 // Create an Instantiation Scope for finalizing the operator.
3849 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003850 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003851 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003852 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003853 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003854 ConversionSpecialized, Info);
3855 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3856
3857 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003858 // to a ptr-to-function, use the deduced arguments from the conversion
3859 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 // e.g., int (*fp)(int) = [](auto a) { return a; };
3861 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003862
Faisal Vali2b3a3012013-10-24 23:40:02 +00003863 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003864 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003865 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003866 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003867 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003868 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003869 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003870 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3871
Simon Pilgrim728134c2016-08-12 11:43:57 +00003872 // Create the corresponding specializations of the call operator and
3873 // the static-invoker; and if the return type is auto,
3874 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003875 // DestFunctionPtrReturnType.
3876 // For instance:
3877 // auto L = [](auto a) { return f(a); };
3878 // int (*fp)(int) = L;
3879 // char (*fp2)(int) = L; <-- Not OK.
3880
3881 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003882 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003883 Info, *this);
3884 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003885 return Result;
3886}
3887
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003888/// \brief Deduce template arguments for a function template when there is
3889/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3890///
3891/// \param FunctionTemplate the function template for which we are performing
3892/// template argument deduction.
3893///
James Dennett18348b62012-06-22 08:52:37 +00003894/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003895/// arguments.
3896///
3897/// \param Specialization if template argument deduction was successful,
3898/// this will be set to the function template specialization produced by
3899/// template argument deduction.
3900///
3901/// \param Info the argument will be updated to provide additional information
3902/// about template argument deduction.
3903///
Richard Smithbaa47832016-12-01 02:11:49 +00003904/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3905/// the address of a function template in a context where we do not have a
3906/// target type, per [over.over]. If \c false, we are looking up a function
3907/// template specialization based on its signature, which only happens when
3908/// deducing a function parameter type from an argument that is a template-id
3909/// naming a function template specialization.
3910///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003911/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003912Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3913 FunctionTemplateDecl *FunctionTemplate,
3914 TemplateArgumentListInfo *ExplicitTemplateArgs,
3915 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3916 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003917 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003918 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003919 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003920}
3921
Richard Smith30482bc2011-02-20 03:19:35 +00003922namespace {
3923 /// Substitute the 'auto' type specifier within a type for a given replacement
3924 /// type.
3925 class SubstituteAutoTransform :
3926 public TreeTransform<SubstituteAutoTransform> {
3927 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003928 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003929 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003930 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3931 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003932 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003933 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003934
Richard Smith30482bc2011-02-20 03:19:35 +00003935 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3936 // If we're building the type pattern to deduce against, don't wrap the
3937 // substituted type in an AutoType. Certain template deduction rules
3938 // apply only when a template type parameter appears directly (and not if
3939 // the parameter is found through desugaring). For instance:
3940 // auto &&lref = lvalue;
3941 // must transform into "rvalue reference to T" not "rvalue reference to
3942 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003943 if (!UseAutoSugar) {
3944 assert(isa<TemplateTypeParmType>(Replacement) &&
3945 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003946 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003947 TemplateTypeParmTypeLoc NewTL =
3948 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003949 NewTL.setNameLoc(TL.getNameLoc());
3950 return Result;
3951 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00003952 QualType Result = SemaRef.Context.getAutoType(
3953 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003954 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3955 NewTL.setNameLoc(TL.getNameLoc());
3956 return Result;
3957 }
3958 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003959
3960 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3961 // Lambdas never need to be transformed.
3962 return E;
3963 }
Richard Smith061f1e22013-04-30 21:23:01 +00003964
Richard Smith2a7d4812013-05-04 07:00:32 +00003965 QualType Apply(TypeLoc TL) {
3966 // Create some scratch storage for the transformed type locations.
3967 // FIXME: We're just going to throw this information away. Don't build it.
3968 TypeLocBuilder TLB;
3969 TLB.reserve(TL.getFullDataSize());
3970 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003971 }
Richard Smith30482bc2011-02-20 03:19:35 +00003972 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003973}
Richard Smith30482bc2011-02-20 03:19:35 +00003974
Richard Smith2a7d4812013-05-04 07:00:32 +00003975Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003976Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
3977 Optional<unsigned> DependentDeductionDepth) {
3978 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
3979 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00003980}
3981
Richard Smith061f1e22013-04-30 21:23:01 +00003982/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003983///
Richard Smith87d263e2016-12-25 08:05:23 +00003984/// Note that this is done even if the initializer is dependent. (This is
3985/// necessary to support partial ordering of templates using 'auto'.)
3986/// A dependent type will be produced when deducing from a dependent type.
3987///
Richard Smith30482bc2011-02-20 03:19:35 +00003988/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003989/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003990/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003991/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00003992/// \param DependentDeductionDepth Set if we should permit deduction in
3993/// dependent cases. This is necessary for template partial ordering with
3994/// 'auto' template parameters. The value specified is the template
3995/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00003996Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003997Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
3998 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00003999 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004000 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4001 if (NonPlaceholder.isInvalid())
4002 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004003 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004004 }
4005
Richard Smith87d263e2016-12-25 08:05:23 +00004006 if (!DependentDeductionDepth &&
4007 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4008 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004009 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004010 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004011 }
4012
Richard Smith87d263e2016-12-25 08:05:23 +00004013 // Find the depth of template parameter to synthesize.
4014 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4015
Richard Smith74aeef52013-04-26 16:15:35 +00004016 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4017 // Since 'decltype(auto)' can only occur at the top of the type, we
4018 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004019 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004020 if (AT->isDecltypeAuto()) {
4021 if (isa<InitListExpr>(Init)) {
4022 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4023 return DAR_FailedAlreadyDiagnosed;
4024 }
4025
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004026 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004027 if (Deduced.isNull())
4028 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004029 // FIXME: Support a non-canonical deduced type for 'auto'.
4030 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004031 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004032 if (Result.isNull())
4033 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004034 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004035 } else if (!getLangOpts().CPlusPlus) {
4036 if (isa<InitListExpr>(Init)) {
4037 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4038 return DAR_FailedAlreadyDiagnosed;
4039 }
Richard Smith74aeef52013-04-26 16:15:35 +00004040 }
4041 }
4042
Richard Smith30482bc2011-02-20 03:19:35 +00004043 SourceLocation Loc = Init->getExprLoc();
4044
4045 LocalInstantiationScope InstScope(*this);
4046
4047 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004048 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4049 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004050 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4051 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004052 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4053 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004054
Richard Smith87d263e2016-12-25 08:05:23 +00004055 QualType FuncParam =
4056 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4057 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004058 assert(!FuncParam.isNull() &&
4059 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004060
4061 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004062 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004063 Deduced.resize(1);
4064 QualType InitType = Init->getType();
4065 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004066
Richard Smith87d263e2016-12-25 08:05:23 +00004067 TemplateDeductionInfo Info(Loc, Depth);
4068
4069 // If deduction failed, don't diagnose if the initializer is dependent; it
4070 // might acquire a matching type in the instantiation.
4071 auto DeductionFailed = [&]() -> DeduceAutoResult {
4072 if (Init->isTypeDependent()) {
4073 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4074 assert(!Result.isNull() && "substituting DependentTy can't fail");
4075 return DAR_Succeeded;
4076 }
4077 return DAR_Failed;
4078 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004079
Richard Smith74801c82012-07-08 04:13:07 +00004080 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004081 if (InitList) {
4082 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004083 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4084 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004085 Info, Deduced, TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004086 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004087 }
4088 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004089 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4090 Diag(Loc, diag::err_auto_bitfield);
4091 return DAR_FailedAlreadyDiagnosed;
4092 }
4093
James Y Knight7a22b242015-08-06 20:26:32 +00004094 if (AdjustFunctionParmAndArgTypesForDeduction(
4095 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004096 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004097
James Y Knight7a22b242015-08-06 20:26:32 +00004098 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4099 FuncParam, InitType, Info, Deduced,
4100 TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004101 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004102 }
Richard Smith30482bc2011-02-20 03:19:35 +00004103
Richard Smith87d263e2016-12-25 08:05:23 +00004104 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004105 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004106 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004107
Eli Friedmane4310952012-11-06 23:56:42 +00004108 QualType DeducedType = Deduced[0].getAsType();
4109
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004110 if (InitList) {
4111 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4112 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004113 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004114 }
4115
Richard Smith061f1e22013-04-30 21:23:01 +00004116 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004117 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004118 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004119
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004120 // Check that the deduced argument type is compatible with the original
4121 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004122 if (!InitList && !Result.isNull() &&
4123 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004124 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004125 Result)) {
4126 Result = QualType();
Richard Smith87d263e2016-12-25 08:05:23 +00004127 return DeductionFailed();
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004128 }
4129
Sebastian Redl09edce02012-01-23 22:09:39 +00004130 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004131}
4132
Simon Pilgrim728134c2016-08-12 11:43:57 +00004133QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004134 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004135 if (TypeToReplaceAuto->isDependentType())
4136 TypeToReplaceAuto = QualType();
4137 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4138 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004139}
4140
Simon Pilgrim728134c2016-08-12 11:43:57 +00004141TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004142 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004143 if (TypeToReplaceAuto->isDependentType())
4144 TypeToReplaceAuto = QualType();
4145 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4146 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004147}
4148
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004149void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4150 if (isa<InitListExpr>(Init))
4151 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004152 VDecl->isInitCapture()
4153 ? diag::err_init_capture_deduction_failure_from_init_list
4154 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004155 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4156 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004157 Diag(VDecl->getLocation(),
4158 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4159 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004160 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4161 << Init->getSourceRange();
4162}
4163
Richard Smith2a7d4812013-05-04 07:00:32 +00004164bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4165 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004166 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004167
4168 if (FD->getTemplateInstantiationPattern())
4169 InstantiateFunctionDefinition(Loc, FD);
4170
Alp Toker314cc812014-01-25 16:55:45 +00004171 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004172 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4173 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4174 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4175 }
4176
4177 return StillUndeduced;
4178}
4179
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004180static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004181MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004182 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004183 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004184 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185
4186/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004187static void
4188AddImplicitObjectParameterType(ASTContext &Context,
4189 CXXMethodDecl *Method,
4190 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004191 // C++11 [temp.func.order]p3:
4192 // [...] The new parameter is of type "reference to cv A," where cv are
4193 // the cv-qualifiers of the function template (if any) and A is
4194 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004195 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004196 // The standard doesn't say explicitly, but we pick the appropriate kind of
4197 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004198 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4199 ArgTy = Context.getQualifiedType(ArgTy,
4200 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004201 if (Method->getRefQualifier() == RQ_RValue)
4202 ArgTy = Context.getRValueReferenceType(ArgTy);
4203 else
4204 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004205 ArgTypes.push_back(ArgTy);
4206}
4207
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004208/// \brief Determine whether the function template \p FT1 is at least as
4209/// specialized as \p FT2.
4210static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004211 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004212 FunctionTemplateDecl *FT1,
4213 FunctionTemplateDecl *FT2,
4214 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004215 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004216 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004218 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4219 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004221 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4222 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004223 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004224 Deduced.resize(TemplateParams->size());
4225
4226 // C++0x [temp.deduct.partial]p3:
4227 // The types used to determine the ordering depend on the context in which
4228 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004229 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004230 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004231 switch (TPOC) {
4232 case TPOC_Call: {
4233 // - In the context of a function call, the function parameter types are
4234 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004235 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4236 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004237
Eli Friedman3b5774a2012-09-19 23:27:04 +00004238 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004239 // [...] If only one of the function templates is a non-static
4240 // member, that function template is considered to have a new
4241 // first parameter inserted in its function parameter list. The
4242 // new parameter is of type "reference to cv A," where cv are
4243 // the cv-qualifiers of the function template (if any) and A is
4244 // the class of which the function template is a member.
4245 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004246 // Note that we interpret this to mean "if one of the function
4247 // templates is a non-static member and the other is a non-member";
4248 // otherwise, the ordering rules for static functions against non-static
4249 // functions don't make any sense.
4250 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004251 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4252 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004253 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004254
Richard Smithe5b52202013-09-11 00:52:39 +00004255 unsigned NumComparedArguments = NumCallArguments1;
4256
4257 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004258 // Compare 'this' from Method1 against first parameter from Method2.
4259 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4260 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004261 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004262 // Compare 'this' from Method2 against first parameter from Method1.
4263 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004264 }
4265
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004266 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004267 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004268 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004269 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregorb837ea42011-01-11 17:34:58 +00004271 // C++ [temp.func.order]p5:
4272 // The presence of unused ellipsis and default arguments has no effect on
4273 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004274 if (Args1.size() > NumComparedArguments)
4275 Args1.resize(NumComparedArguments);
4276 if (Args2.size() > NumComparedArguments)
4277 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004278 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4279 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004280 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004281 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 break;
4284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 case TPOC_Conversion:
4287 // - In the context of a call to a conversion operator, the return types
4288 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004289 if (DeduceTemplateArgumentsByTypeMatch(
4290 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
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;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004296 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004297 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004298 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004299 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4300 FD2->getType(), FD1->getType(),
4301 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004302 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004303 return false;
4304 break;
4305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004307 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308 // In most cases, all template parameters must have values in order for
4309 // deduction to succeed, but for partial ordering purposes a template
4310 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004311 // types being used for partial ordering. [ Note: a template parameter used
4312 // in a non-deduced context is considered used. -end note]
4313 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4314 for (; ArgIdx != NumArgs; ++ArgIdx)
4315 if (Deduced[ArgIdx].isNull())
4316 break;
4317
4318 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004320 // as FT2.
4321 return true;
4322 }
4323
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004324 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004325 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004326 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004327 case TPOC_Call:
4328 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4329 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004330 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004331 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004332 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004334 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004335 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4336 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004337 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004339 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004340 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004341 TemplateParams->getDepth(),
4342 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004343 break;
4344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004346 for (; ArgIdx != NumArgs; ++ArgIdx)
4347 // If this argument had no value deduced but was used in one of the types
4348 // used for partial ordering, then deduction fails.
4349 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4350 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004352 return true;
4353}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Douglas Gregorcef1a032011-01-16 16:03:23 +00004355/// \brief Determine whether this a function template whose parameter-type-list
4356/// ends with a function parameter pack.
4357static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4358 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4359 unsigned NumParams = Function->getNumParams();
4360 if (NumParams == 0)
4361 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362
Douglas Gregorcef1a032011-01-16 16:03:23 +00004363 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4364 if (!Last->isParameterPack())
4365 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366
Douglas Gregorcef1a032011-01-16 16:03:23 +00004367 // Make sure that no previous parameter is a parameter pack.
4368 while (--NumParams > 0) {
4369 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4370 return false;
4371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
Douglas Gregorcef1a032011-01-16 16:03:23 +00004373 return true;
4374}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregorbe999392009-09-15 16:23:51 +00004376/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004377/// to the rules of function template partial ordering (C++ [temp.func.order]).
4378///
4379/// \param FT1 the first function template
4380///
4381/// \param FT2 the second function template
4382///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383/// \param TPOC the context in which we are performing partial ordering of
4384/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004385///
Richard Smithe5b52202013-09-11 00:52:39 +00004386/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4387/// only when \c TPOC is \c TPOC_Call.
4388///
4389/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4390/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004391///
Douglas Gregorbe999392009-09-15 16:23:51 +00004392/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004393/// template is more specialized, returns NULL.
4394FunctionTemplateDecl *
4395Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4396 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004397 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004398 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004399 unsigned NumCallArguments1,
4400 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004402 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004404 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004406 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004407 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004409 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004410 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004411
Douglas Gregorcef1a032011-01-16 16:03:23 +00004412 // FIXME: This mimics what GCC implements, but doesn't match up with the
4413 // proposed resolution for core issue 692. This area needs to be sorted out,
4414 // but for now we attempt to maintain compatibility.
4415 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4416 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4417 if (Variadic1 != Variadic2)
4418 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Craig Topperc3ec1492014-05-26 06:22:03 +00004420 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004421}
Douglas Gregor9b146582009-07-08 20:55:45 +00004422
Douglas Gregor450f00842009-09-25 18:43:00 +00004423/// \brief Determine if the two templates are equivalent.
4424static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4425 if (T1 == T2)
4426 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregor450f00842009-09-25 18:43:00 +00004428 if (!T1 || !T2)
4429 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregor450f00842009-09-25 18:43:00 +00004431 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4432}
4433
4434/// \brief Retrieve the most specialized of the given function template
4435/// specializations.
4436///
John McCall58cc69d2010-01-27 01:50:18 +00004437/// \param SpecBegin the start iterator of the function template
4438/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004439///
John McCall58cc69d2010-01-27 01:50:18 +00004440/// \param SpecEnd the end iterator of the function template
4441/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004442///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004444/// diagnostic should occur.
4445///
4446/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4447/// no matching candidates.
4448///
4449/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4450/// occurs.
4451///
4452/// \param CandidateDiag partial diagnostic used for each function template
4453/// specialization that is a candidate in the ambiguous ordering. One parameter
4454/// in this diagnostic should be unbound, which will correspond to the string
4455/// describing the template arguments for the function template specialization.
4456///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004458/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004459UnresolvedSetIterator Sema::getMostSpecialized(
4460 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4461 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004462 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4463 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4464 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004465 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004466 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004467 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004468 FailedCandidates.NoteCandidates(*this, Loc);
4469 }
John McCall58cc69d2010-01-27 01:50:18 +00004470 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
4473 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004474 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor450f00842009-09-25 18:43:00 +00004476 // Find the function template that is better than all of the templates it
4477 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004478 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004480 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004482 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4483 FunctionTemplateDecl *Challenger
4484 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004485 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004486 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004487 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004488 Challenger)) {
4489 Best = I;
4490 BestTemplate = Challenger;
4491 }
4492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregor450f00842009-09-25 18:43:00 +00004494 // Make sure that the "best" function template is more specialized than all
4495 // of the others.
4496 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004497 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4498 FunctionTemplateDecl *Challenger
4499 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004500 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004502 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004503 BestTemplate)) {
4504 Ambiguous = true;
4505 break;
4506 }
4507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Douglas Gregor450f00842009-09-25 18:43:00 +00004509 if (!Ambiguous) {
4510 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004511 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregor450f00842009-09-25 18:43:00 +00004514 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004515 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004516 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Richard Smithb875c432013-05-04 01:51:08 +00004518 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004519 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4520 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004521 const auto *FD = cast<FunctionDecl>(*I);
4522 PD << FD << getTemplateArgumentBindingsText(
4523 FD->getPrimaryTemplate()->getTemplateParameters(),
4524 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004525 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004526 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004527 Diag((*I)->getLocation(), PD);
4528 }
Richard Smithb875c432013-05-04 01:51:08 +00004529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530
John McCall58cc69d2010-01-27 01:50:18 +00004531 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004532}
4533
Richard Smith0da6dc42016-12-24 16:40:51 +00004534/// Determine whether one partial specialization, P1, is at least as
4535/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004536///
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00004537/// \tparam PartialSpecializationDecl The kind of P2, which must be a
Richard Smith0da6dc42016-12-24 16:40:51 +00004538/// {Class,Var}TemplatePartialSpecializationDecl.
4539/// \param T1 The injected-class-name of P1 (faked for a variable template).
4540/// \param T2 The injected-class-name of P2 (faked for a variable template).
4541/// \param Loc The location at which the comparison is required.
4542template<typename PartialSpecializationDecl>
4543static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4544 PartialSpecializationDecl *P2,
4545 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004546 // C++ [temp.class.order]p1:
4547 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 // specialized as the second if, given the following rewrite to two
4549 // function templates, the first function template is at least as
4550 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004551 // templates (14.6.6.2):
4552 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553 // first partial specialization and has a single function parameter
4554 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004555 // arguments of the first partial specialization, and
4556 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557 // second partial specialization and has a single function parameter
4558 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004559 // arguments of the second partial specialization.
4560 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004561 // Rather than synthesize function templates, we merely perform the
4562 // equivalent partial ordering by performing deduction directly on
4563 // the template arguments of the class template partial
4564 // specializations. This computation is slightly simpler than the
4565 // general problem of function template partial ordering, because
4566 // class template partial specializations are more constrained. We
4567 // know that every template parameter is deducible from the class
4568 // template partial specialization's template arguments, for
4569 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004570 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004571 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004572
Richard Smith0da6dc42016-12-24 16:40:51 +00004573 // Determine whether P1 is at least as specialized as P2.
4574 Deduced.resize(P2->getTemplateParameters()->size());
4575 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4576 T2, T1, Info, Deduced, TDF_None,
4577 /*PartialOrdering=*/true))
4578 return false;
4579
4580 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4581 Deduced.end());
4582 Sema::InstantiatingTemplate Inst(S, Loc, P2, DeducedArgs, Info);
4583 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4584 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004585 S, P2, /*PartialOrdering=*/true,
4586 TemplateArgumentList(TemplateArgumentList::OnStack,
4587 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004588 Deduced, Info))
4589 return false;
4590
4591 return true;
4592}
4593
4594/// \brief Returns the more specialized class template partial specialization
4595/// according to the rules of partial ordering of class template partial
4596/// specializations (C++ [temp.class.order]).
4597///
4598/// \param PS1 the first class template partial specialization
4599///
4600/// \param PS2 the second class template partial specialization
4601///
4602/// \returns the more specialized class template partial specialization. If
4603/// neither partial specialization is more specialized, returns NULL.
4604ClassTemplatePartialSpecializationDecl *
4605Sema::getMoreSpecializedPartialSpecialization(
4606 ClassTemplatePartialSpecializationDecl *PS1,
4607 ClassTemplatePartialSpecializationDecl *PS2,
4608 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004609 QualType PT1 = PS1->getInjectedSpecializationType();
4610 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611
Richard Smith0da6dc42016-12-24 16:40:51 +00004612 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4613 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004614
4615 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004616 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004617
4618 return Better1 ? PS1 : PS2;
4619}
4620
Larisse Voufo39a1e502013-08-06 01:03:05 +00004621VarTemplatePartialSpecializationDecl *
4622Sema::getMoreSpecializedPartialSpecialization(
4623 VarTemplatePartialSpecializationDecl *PS1,
4624 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004625 // Pretend the variable template specializations are class template
4626 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004627 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004628 "the partial specializations being compared should specialize"
4629 " the same template.");
4630 TemplateName Name(PS1->getSpecializedTemplate());
4631 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4632 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004633 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004634 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004635 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004636
Richard Smith0da6dc42016-12-24 16:40:51 +00004637 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4638 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregorbe999392009-09-15 16:23:51 +00004640 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004641 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642
Richard Smith0da6dc42016-12-24 16:40:51 +00004643 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004644}
4645
Mike Stump11289f42009-09-09 15:08:12 +00004646static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004647MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004648 const TemplateArgument &TemplateArg,
4649 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004650 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004651 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004652
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004653/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004654/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004655static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004656MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004657 const Expr *E,
4658 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004659 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004660 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004661 // We can deduce from a pack expansion.
4662 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4663 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Richard Smith34349002012-07-09 03:07:20 +00004665 // Skip through any implicit casts we added while type-checking, and any
4666 // substitutions performed by template alias expansion.
4667 while (1) {
4668 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4669 E = ICE->getSubExpr();
4670 else if (const SubstNonTypeTemplateParmExpr *Subst =
4671 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4672 E = Subst->getReplacement();
4673 else
4674 break;
4675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
4677 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004678 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004679 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004680 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004681 return;
4682
Mike Stump11289f42009-09-09 15:08:12 +00004683 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004684 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4685 if (!NTTP)
4686 return;
4687
Douglas Gregor21610382009-10-29 00:04:11 +00004688 if (NTTP->getDepth() == Depth)
4689 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004690
4691 // In C++1z mode, additional arguments may be deduced from the type of a
4692 // non-type argument.
4693 if (Ctx.getLangOpts().CPlusPlus1z)
4694 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004695}
4696
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004697/// \brief Mark the template parameters that are used by the given
4698/// nested name specifier.
4699static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004700MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004701 NestedNameSpecifier *NNS,
4702 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004703 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004704 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004705 if (!NNS)
4706 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004708 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004709 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004710 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004711 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004712}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004714/// \brief Mark the template parameters that are used by the given
4715/// template name.
4716static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004717MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004718 TemplateName Name,
4719 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004720 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004721 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004722 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4723 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004724 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4725 if (TTP->getDepth() == Depth)
4726 Used[TTP->getIndex()] = true;
4727 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004728 return;
4729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004731 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004732 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004733 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004734 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004735 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004736 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004737}
4738
4739/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004740/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004741static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004742MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004743 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004744 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004745 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004746 if (T.isNull())
4747 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Douglas Gregor91772d12009-06-13 00:26:55 +00004749 // Non-dependent types have nothing deducible
4750 if (!T->isDependentType())
4751 return;
4752
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004753 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004754 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004755 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004756 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004757 cast<PointerType>(T)->getPointeeType(),
4758 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004759 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004761 break;
4762
4763 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004764 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004765 cast<BlockPointerType>(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::LValueReference:
4772 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004773 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004774 cast<ReferenceType>(T)->getPointeeType(),
4775 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004776 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004777 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004778 break;
4779
4780 case Type::MemberPointer: {
4781 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004782 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004783 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004784 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004785 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004786 break;
4787 }
4788
4789 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004790 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004791 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004792 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004793 // Fall through to check the element type
4794
4795 case Type::ConstantArray:
4796 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004797 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004799 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004800 break;
4801
4802 case Type::Vector:
4803 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004804 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004805 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004806 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004807 break;
4808
Douglas Gregor758a8692009-06-17 21:51:59 +00004809 case Type::DependentSizedExtVector: {
4810 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004811 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004812 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004813 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004814 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004815 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004816 break;
4817 }
4818
Douglas Gregor91772d12009-06-13 00:26:55 +00004819 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004820 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004821 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4822 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004823 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4824 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004825 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004826 break;
4827 }
4828
Douglas Gregor21610382009-10-29 00:04:11 +00004829 case Type::TemplateTypeParm: {
4830 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4831 if (TTP->getDepth() == Depth)
4832 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004833 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004834 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004835
Douglas Gregorfb322d82011-01-14 05:11:40 +00004836 case Type::SubstTemplateTypeParmPack: {
4837 const SubstTemplateTypeParmPackType *Subst
4838 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004839 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004840 QualType(Subst->getReplacedParameter(), 0),
4841 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004842 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004843 OnlyDeduced, Depth, Used);
4844 break;
4845 }
4846
John McCall2408e322010-04-27 00:57:59 +00004847 case Type::InjectedClassName:
4848 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4849 // fall through
4850
Douglas Gregor91772d12009-06-13 00:26:55 +00004851 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004852 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004853 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004854 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004855 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Douglas Gregord0ad2942010-12-23 01:24:45 +00004857 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004858 // If the template argument list of P contains a pack expansion that is
4859 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004860 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004862 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004863 break;
4864
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004865 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004866 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004867 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004868 break;
4869 }
4870
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 case Type::Complex:
4872 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004873 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004874 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004875 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004876 break;
4877
Eli Friedman0dfb8892011-10-06 23:00:33 +00004878 case Type::Atomic:
4879 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004880 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004881 cast<AtomicType>(T)->getValueType(),
4882 OnlyDeduced, Depth, Used);
4883 break;
4884
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004885 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004886 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004887 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004888 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004889 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004890 break;
4891
John McCallc392f372010-06-11 00:33:02 +00004892 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004893 // C++14 [temp.deduct.type]p5:
4894 // The non-deduced contexts are:
4895 // -- The nested-name-specifier of a type that was specified using a
4896 // qualified-id
4897 //
4898 // C++14 [temp.deduct.type]p6:
4899 // When a type name is specified in a way that includes a non-deduced
4900 // context, all of the types that comprise that type name are also
4901 // non-deduced.
4902 if (OnlyDeduced)
4903 break;
4904
John McCallc392f372010-06-11 00:33:02 +00004905 const DependentTemplateSpecializationType *Spec
4906 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004907
Richard Smith50d5b972015-12-30 20:56:05 +00004908 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4909 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004910
John McCallc392f372010-06-11 00:33:02 +00004911 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004912 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004913 Used);
4914 break;
4915 }
4916
John McCallbd8d9bd2010-03-01 23:49:17 +00004917 case Type::TypeOf:
4918 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004919 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004920 cast<TypeOfType>(T)->getUnderlyingType(),
4921 OnlyDeduced, Depth, Used);
4922 break;
4923
4924 case Type::TypeOfExpr:
4925 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004926 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004927 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4928 OnlyDeduced, Depth, Used);
4929 break;
4930
4931 case Type::Decltype:
4932 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004933 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004934 cast<DecltypeType>(T)->getUnderlyingExpr(),
4935 OnlyDeduced, Depth, Used);
4936 break;
4937
Alexis Hunte852b102011-05-24 22:41:36 +00004938 case Type::UnaryTransform:
4939 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004940 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00004941 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00004942 OnlyDeduced, Depth, Used);
4943 break;
4944
Douglas Gregord2fa7662010-12-20 02:24:11 +00004945 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004946 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004947 cast<PackExpansionType>(T)->getPattern(),
4948 OnlyDeduced, Depth, Used);
4949 break;
4950
Richard Smith30482bc2011-02-20 03:19:35 +00004951 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004952 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004953 cast<AutoType>(T)->getDeducedType(),
4954 OnlyDeduced, Depth, Used);
4955
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004956 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004957 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004958 case Type::VariableArray:
4959 case Type::FunctionNoProto:
4960 case Type::Record:
4961 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004962 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004963 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004964 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004965 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004966 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004967#define TYPE(Class, Base)
4968#define ABSTRACT_TYPE(Class, Base)
4969#define DEPENDENT_TYPE(Class, Base)
4970#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4971#include "clang/AST/TypeNodes.def"
4972 break;
4973 }
4974}
4975
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004976/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004977/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004978static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004979MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004980 const TemplateArgument &TemplateArg,
4981 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004982 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004983 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004984 switch (TemplateArg.getKind()) {
4985 case TemplateArgument::Null:
4986 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004987 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004988 break;
Mike Stump11289f42009-09-09 15:08:12 +00004989
Eli Friedmanb826a002012-09-26 02:36:12 +00004990 case TemplateArgument::NullPtr:
4991 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4992 Depth, Used);
4993 break;
4994
Douglas Gregor91772d12009-06-13 00:26:55 +00004995 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004996 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004997 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004998 break;
4999
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005000 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005001 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005002 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005004 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005005 break;
5006
5007 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005008 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005009 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005010 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Anders Carlssonbc343912009-06-15 17:04:53 +00005012 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005013 for (const auto &P : TemplateArg.pack_elements())
5014 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005015 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005016 }
5017}
5018
James Dennett41725122012-06-22 10:16:05 +00005019/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005020/// template argument list.
5021///
5022/// \param TemplateArgs the template argument list from which template
5023/// parameters will be deduced.
5024///
James Dennett41725122012-06-22 10:16:05 +00005025/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005026/// to indicate when the corresponding template parameter will be
5027/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005028void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005029Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005030 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005031 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005032 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033 // If the template argument list of P contains a pack expansion that is not
5034 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005035 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005037 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005038 return;
5039
Douglas Gregor91772d12009-06-13 00:26:55 +00005040 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005041 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005042 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005043}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005044
5045/// \brief Marks all of the template parameters that will be deduced by a
5046/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005047void Sema::MarkDeducedTemplateParameters(
5048 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5049 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005051 = FunctionTemplate->getTemplateParameters();
5052 Deduced.clear();
5053 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054
Douglas Gregorce23bae2009-09-18 23:21:38 +00005055 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5056 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005057 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005058 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005059}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005060
5061bool hasDeducibleTemplateParameters(Sema &S,
5062 FunctionTemplateDecl *FunctionTemplate,
5063 QualType T) {
5064 if (!T->isDependentType())
5065 return false;
5066
5067 TemplateParameterList *TemplateParams
5068 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005069 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005070 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005071 Deduced);
5072
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005073 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005074}