blob: dc291836fb94db78415070c1afda0cbf2bd351c6 [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) {
Richard Smith5d102892016-12-27 03:59:58 +0000383 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
384 DeducedTemplateArgument(Value),
385 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000386}
387
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000388/// \brief Deduce the value of the given non-type template parameter
389/// from the given declaration.
390///
391/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000392static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
393 Sema &S, TemplateParameterList *TemplateParams,
394 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
395 TemplateDeductionInfo &Info,
396 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000397 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000398 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000399 return DeduceNonTypeTemplateArgument(
400 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000401}
402
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000403static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000404DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000405 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000406 TemplateName Param,
407 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000408 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000409 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000410 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 if (!ParamDecl) {
412 // The parameter type is dependent and is not a template template parameter,
413 // so there is nothing that we can deduce.
414 return Sema::TDK_Success;
415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
Douglas Gregoradee3e32009-11-11 23:06:43 +0000417 if (TemplateTemplateParmDecl *TempParam
418 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000419 // If we're not deducing at this depth, there's nothing to deduce.
420 if (TempParam->getDepth() != Info.getDeducedDepth())
421 return Sema::TDK_Success;
422
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000423 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000425 Deduced[TempParam->getIndex()],
426 NewDeduced);
427 if (Result.isNull()) {
428 Info.Param = TempParam;
429 Info.FirstArg = Deduced[TempParam->getIndex()];
430 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000434 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregoradee3e32009-11-11 23:06:43 +0000438 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000439 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000440 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 // Mismatch of non-dependent template parameter to argument.
443 Info.FirstArg = TemplateArgument(Param);
444 Info.SecondArg = TemplateArgument(Arg);
445 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000446}
447
Mike Stump11289f42009-09-09 15:08:12 +0000448/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000449/// type (which is a template-id) with the template argument type.
450///
Chandler Carruthc1263112010-02-07 21:33:28 +0000451/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000452///
453/// \param TemplateParams the template parameters that we are deducing
454///
455/// \param Param the parameter type
456///
457/// \param Arg the argument type
458///
459/// \param Info information about the template argument deduction itself
460///
461/// \param Deduced the deduced template arguments
462///
463/// \returns the result of template argument deduction so far. Note that a
464/// "success" result means that template argument deduction has not yet failed,
465/// but it may still fail, later, for other reasons.
466static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000467DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000468 TemplateParameterList *TemplateParams,
469 const TemplateSpecializationType *Param,
470 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000471 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000472 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000473 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregore81f3e72009-07-07 23:09:34 +0000475 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000476 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477 = dyn_cast<TemplateSpecializationType>(Arg)) {
478 // Perform template argument deduction for the template name.
479 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000480 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000481 Param->getTemplateName(),
482 SpecArg->getTemplateName(),
483 Info, Deduced))
484 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Mike Stump11289f42009-09-09 15:08:12 +0000486
Douglas Gregore81f3e72009-07-07 23:09:34 +0000487 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000488 // argument. Ignore any missing/extra arguments, since they could be
489 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000490 return DeduceTemplateArguments(S, TemplateParams,
491 Param->template_arguments(),
492 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000493 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregore81f3e72009-07-07 23:09:34 +0000496 // If the argument type is a class template specialization, we
497 // perform template argument deduction using its template
498 // arguments.
499 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000500 if (!RecordArg) {
501 Info.FirstArg = TemplateArgument(QualType(Param, 0));
502 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000503 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
506 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000508 if (!SpecArg) {
509 Info.FirstArg = TemplateArgument(QualType(Param, 0));
510 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000511 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 // Perform template argument deduction for the template name.
515 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000516 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000517 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000518 Param->getTemplateName(),
519 TemplateName(SpecArg->getSpecializedTemplate()),
520 Info, Deduced))
521 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregor7baabef2010-12-22 18:17:10 +0000523 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000524 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
525 SpecArg->getTemplateArgs().asArray(), Info,
526 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000527}
528
John McCall08569062010-08-28 22:14:41 +0000529/// \brief Determines whether the given type is an opaque type that
530/// might be more qualified when instantiated.
531static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
532 switch (T->getTypeClass()) {
533 case Type::TypeOfExpr:
534 case Type::TypeOf:
535 case Type::DependentName:
536 case Type::Decltype:
537 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000538 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000539 return true;
540
541 case Type::ConstantArray:
542 case Type::IncompleteArray:
543 case Type::VariableArray:
544 case Type::DependentSizedArray:
545 return IsPossiblyOpaquelyQualifiedType(
546 cast<ArrayType>(T)->getElementType());
547
548 default:
549 return false;
550 }
551}
552
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000553/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000555getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000556 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
557 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
560 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Douglas Gregor5499af42011-01-05 23:12:31 +0000562 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
563 return std::make_pair(TTP->getDepth(), TTP->getIndex());
564}
565
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000566/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000568getDepthAndIndex(UnexpandedParameterPack UPP) {
569 if (const TemplateTypeParmType *TTP
570 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
571 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000573 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
574}
575
Douglas Gregor5499af42011-01-05 23:12:31 +0000576/// \brief Helper function to build a TemplateParameter when we don't
577/// know its type statically.
578static TemplateParameter makeTemplateParameter(Decl *D) {
579 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
580 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000581 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000582 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor5499af42011-01-05 23:12:31 +0000584 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
585}
586
Richard Smith0a80d572014-05-29 01:12:14 +0000587/// A pack that we're currently deducing.
588struct clang::DeducedPack {
589 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000590
Richard Smith0a80d572014-05-29 01:12:14 +0000591 // The index of the pack.
592 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // The old value of the pack before we started deducing it.
595 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000596
Richard Smith0a80d572014-05-29 01:12:14 +0000597 // A deferred value of this pack from an inner deduction, that couldn't be
598 // deduced because this deduction hadn't happened yet.
599 DeducedTemplateArgument DeferredDeduction;
600
601 // The new value of the pack.
602 SmallVector<DeducedTemplateArgument, 4> New;
603
604 // The outer deduction for this pack, if any.
605 DeducedPack *Outer;
606};
607
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000608namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000609/// A scope in which we're performing pack deduction.
610class PackDeductionScope {
611public:
612 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
613 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
614 TemplateDeductionInfo &Info, TemplateArgument Pattern)
615 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
616 // Compute the set of template parameter indices that correspond to
617 // parameter packs expanded by the pack expansion.
618 {
619 llvm::SmallBitVector SawIndices(TemplateParams->size());
620 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
621 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
622 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
623 unsigned Depth, Index;
624 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000625 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000626 SawIndices[Index] = true;
627
628 // Save the deduced template argument for the parameter pack expanded
629 // by this pack expansion, then clear out the deduction.
630 DeducedPack Pack(Index);
631 Pack.Saved = Deduced[Index];
632 Deduced[Index] = TemplateArgument();
633
634 Packs.push_back(Pack);
635 }
636 }
637 }
638 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
639
640 for (auto &Pack : Packs) {
641 if (Info.PendingDeducedPacks.size() > Pack.Index)
642 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
643 else
644 Info.PendingDeducedPacks.resize(Pack.Index + 1);
645 Info.PendingDeducedPacks[Pack.Index] = &Pack;
646
647 if (S.CurrentInstantiationScope) {
648 // If the template argument pack was explicitly specified, add that to
649 // the set of deduced arguments.
650 const TemplateArgument *ExplicitArgs;
651 unsigned NumExplicitArgs;
652 NamedDecl *PartiallySubstitutedPack =
653 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
654 &ExplicitArgs, &NumExplicitArgs);
655 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000656 getDepthAndIndex(PartiallySubstitutedPack) ==
657 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000658 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
659 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000660 }
661 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000662
Richard Smith0a80d572014-05-29 01:12:14 +0000663 ~PackDeductionScope() {
664 for (auto &Pack : Packs)
665 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667
Richard Smith0a80d572014-05-29 01:12:14 +0000668 /// Move to deducing the next element in each pack that is being deduced.
669 void nextPackElement() {
670 // Capture the deduced template arguments for each parameter pack expanded
671 // by this pack expansion, add them to the list of arguments we've deduced
672 // for that pack, then clear out the deduced argument.
673 for (auto &Pack : Packs) {
674 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
675 if (!DeducedArg.isNull()) {
676 Pack.New.push_back(DeducedArg);
677 DeducedArg = DeducedTemplateArgument();
678 }
679 }
680 }
681
682 /// \brief Finish template argument deduction for a set of argument packs,
683 /// producing the argument packs and checking for consistency with prior
684 /// deductions.
685 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
686 // Build argument packs for each of the parameter packs expanded by this
687 // pack expansion.
688 for (auto &Pack : Packs) {
689 // Put back the old value for this pack.
690 Deduced[Pack.Index] = Pack.Saved;
691
692 // Build or find a new value for this pack.
693 DeducedTemplateArgument NewPack;
694 if (HasAnyArguments && Pack.New.empty()) {
695 if (Pack.DeferredDeduction.isNull()) {
696 // We were not able to deduce anything for this parameter pack
697 // (because it only appeared in non-deduced contexts), so just
698 // restore the saved argument pack.
699 continue;
700 }
701
702 NewPack = Pack.DeferredDeduction;
703 Pack.DeferredDeduction = TemplateArgument();
704 } else if (Pack.New.empty()) {
705 // If we deduced an empty argument pack, create it now.
706 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
707 } else {
708 TemplateArgument *ArgumentPack =
709 new (S.Context) TemplateArgument[Pack.New.size()];
710 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
711 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000712 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000713 Pack.New[0].wasDeducedFromArrayBound());
714 }
715
716 // Pick where we're going to put the merged pack.
717 DeducedTemplateArgument *Loc;
718 if (Pack.Outer) {
719 if (Pack.Outer->DeferredDeduction.isNull()) {
720 // Defer checking this pack until we have a complete pack to compare
721 // it against.
722 Pack.Outer->DeferredDeduction = NewPack;
723 continue;
724 }
725 Loc = &Pack.Outer->DeferredDeduction;
726 } else {
727 Loc = &Deduced[Pack.Index];
728 }
729
730 // Check the new pack matches any previous value.
731 DeducedTemplateArgument OldPack = *Loc;
732 DeducedTemplateArgument Result =
733 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
734
735 // If we deferred a deduction of this pack, check that one now too.
736 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
737 OldPack = Result;
738 NewPack = Pack.DeferredDeduction;
739 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
740 }
741
742 if (Result.isNull()) {
743 Info.Param =
744 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
745 Info.FirstArg = OldPack;
746 Info.SecondArg = NewPack;
747 return Sema::TDK_Inconsistent;
748 }
749
750 *Loc = Result;
751 }
752
753 return Sema::TDK_Success;
754 }
755
756private:
757 Sema &S;
758 TemplateParameterList *TemplateParams;
759 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
760 TemplateDeductionInfo &Info;
761
762 SmallVector<DeducedPack, 2> Packs;
763};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000764} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000765
Douglas Gregor5499af42011-01-05 23:12:31 +0000766/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767/// types to the list of argument types, as in the parameter-type-lists of
768/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000769///
770/// \param S The semantic analysis object within which we are deducing
771///
772/// \param TemplateParams The template parameters that we are deducing
773///
774/// \param Params The list of parameter types
775///
776/// \param NumParams The number of types in \c Params
777///
778/// \param Args The list of argument types
779///
780/// \param NumArgs The number of types in \c Args
781///
782/// \param Info information about the template argument deduction itself
783///
784/// \param Deduced the deduced template arguments
785///
786/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
787/// how template argument deduction is performed.
788///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000789/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000791/// (C++0x [temp.deduct.partial]).
792///
Douglas Gregor5499af42011-01-05 23:12:31 +0000793/// \returns the result of template argument deduction so far. Note that a
794/// "success" result means that template argument deduction has not yet failed,
795/// but it may still fail, later, for other reasons.
796static Sema::TemplateDeductionResult
797DeduceTemplateArguments(Sema &S,
798 TemplateParameterList *TemplateParams,
799 const QualType *Params, unsigned NumParams,
800 const QualType *Args, unsigned NumArgs,
801 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000802 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000803 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000804 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000805 // Fast-path check to see if we have too many/too few arguments.
806 if (NumParams != NumArgs &&
807 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
808 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // Similarly, if P has a form that contains (T), then each parameter type
813 // Pi of the respective parameter-type- list of P is compared with the
814 // corresponding parameter type Ai of the corresponding parameter-type-list
815 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000816 unsigned ArgIdx = 0, ParamIdx = 0;
817 for (; ParamIdx != NumParams; ++ParamIdx) {
818 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000820 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
821 if (!Expansion) {
822 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // Make sure we have an argument.
825 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000826 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000828 if (isa<PackExpansionType>(Args[ArgIdx])) {
829 // C++0x [temp.deduct.type]p22:
830 // If the original function parameter associated with A is a function
831 // parameter pack and the function parameter associated with P is not
832 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000833 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor5499af42011-01-05 23:12:31 +0000836 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000837 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
838 Params[ParamIdx], Args[ArgIdx],
839 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000840 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 ++ArgIdx;
844 continue;
845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000847 // C++0x [temp.deduct.type]p5:
848 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000850 // parameter-declaration-clause.
851 if (ParamIdx + 1 < NumParams)
852 return Sema::TDK_Success;
853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 // comparison deduces template arguments for subsequent positions in the
859 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000862 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 bool HasAnyArguments = false;
865 for (; ArgIdx < NumArgs; ++ArgIdx) {
866 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
871 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000872 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000873 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
Richard Smith0a80d572014-05-29 01:12:14 +0000875 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000877
Douglas Gregor5499af42011-01-05 23:12:31 +0000878 // Build argument packs for each of the parameter packs expanded by this
879 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000880 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883
Douglas Gregor5499af42011-01-05 23:12:31 +0000884 // Make sure we don't have any extra arguments.
885 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000886 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Douglas Gregor5499af42011-01-05 23:12:31 +0000888 return Sema::TDK_Success;
889}
890
Douglas Gregor1d684c22011-04-28 00:56:09 +0000891/// \brief Determine whether the parameter has qualifiers that are either
892/// inconsistent with or a superset of the argument's qualifiers.
893static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
894 QualType ArgType) {
895 Qualifiers ParamQs = ParamType.getQualifiers();
896 Qualifiers ArgQs = ArgType.getQualifiers();
897
898 if (ParamQs == ArgQs)
899 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000900
Douglas Gregor1d684c22011-04-28 00:56:09 +0000901 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000902 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000903 ParamQs.hasObjCGCAttr())
904 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000905
Douglas Gregor1d684c22011-04-28 00:56:09 +0000906 // Mismatched (but not missing) address spaces.
907 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
908 ParamQs.hasAddressSpace())
909 return true;
910
John McCall31168b02011-06-15 23:02:42 +0000911 // Mismatched (but not missing) Objective-C lifetime qualifiers.
912 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
913 ParamQs.hasObjCLifetime())
914 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000915
Douglas Gregor1d684c22011-04-28 00:56:09 +0000916 // CVR qualifier superset.
917 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
918 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
919 == ParamQs.getCVRQualifiers());
920}
921
Douglas Gregor19a41f12013-04-17 08:45:07 +0000922/// \brief Compare types for equality with respect to possibly compatible
923/// function types (noreturn adjustment, implicit calling conventions). If any
924/// of parameter and argument is not a function, just perform type comparison.
925///
926/// \param Param the template parameter type.
927///
928/// \param Arg the argument type.
929bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
930 CanQualType Arg) {
931 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
932 *ArgFunction = Arg->getAs<FunctionType>();
933
934 // Just compare if not functions.
935 if (!ParamFunction || !ArgFunction)
936 return Param == Arg;
937
Richard Smith3c4f8d22016-10-16 17:54:23 +0000938 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000939 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000940 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000941 return Arg == Context.getCanonicalType(AdjustedParam);
942
943 // FIXME: Compatible calling conventions.
944
945 return Param == Arg;
946}
947
Douglas Gregorcceb9752009-06-26 18:27:22 +0000948/// \brief Deduce the template arguments by comparing the parameter type and
949/// the argument type (C++ [temp.deduct.type]).
950///
Chandler Carruthc1263112010-02-07 21:33:28 +0000951/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000952///
953/// \param TemplateParams the template parameters that we are deducing
954///
955/// \param ParamIn the parameter type
956///
957/// \param ArgIn the argument type
958///
959/// \param Info information about the template argument deduction itself
960///
961/// \param Deduced the deduced template arguments
962///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000963/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000964/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000965///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000966/// \param PartialOrdering Whether we're performing template argument deduction
967/// in the context of partial ordering (C++0x [temp.deduct.partial]).
968///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000969/// \returns the result of template argument deduction so far. Note that a
970/// "success" result means that template argument deduction has not yet failed,
971/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000972static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000973DeduceTemplateArgumentsByTypeMatch(Sema &S,
974 TemplateParameterList *TemplateParams,
975 QualType ParamIn, QualType ArgIn,
976 TemplateDeductionInfo &Info,
977 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
978 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000979 bool PartialOrdering,
980 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000981 // We only want to look at the canonical types, since typedefs and
982 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000983 QualType Param = S.Context.getCanonicalType(ParamIn);
984 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000985
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000986 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000988 if (const PackExpansionType *ArgExpansion
989 = dyn_cast<PackExpansionType>(Arg))
990 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991
Douglas Gregorb837ea42011-01-11 17:34:58 +0000992 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000993 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994 // Before the partial ordering is done, certain transformations are
995 // performed on the types used for partial ordering:
996 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000997 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
998 if (ParamRef)
999 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000
Douglas Gregorb837ea42011-01-11 17:34:58 +00001001 // - If A is a reference type, A is replaced by the type referred to.
1002 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1003 if (ArgRef)
1004 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
Richard Smithed563c22015-02-20 04:45:22 +00001006 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1007 // C++11 [temp.deduct.partial]p9:
1008 // If, for a given type, deduction succeeds in both directions (i.e.,
1009 // the types are identical after the transformations above) and both
1010 // P and A were reference types [...]:
1011 // - if [one type] was an lvalue reference and [the other type] was
1012 // not, [the other type] is not considered to be at least as
1013 // specialized as [the first type]
1014 // - if [one type] is more cv-qualified than [the other type],
1015 // [the other type] is not considered to be at least as specialized
1016 // as [the first type]
1017 // Objective-C ARC adds:
1018 // - [one type] has non-trivial lifetime, [the other type] has
1019 // __unsafe_unretained lifetime, and the types are otherwise
1020 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001021 //
Richard Smithed563c22015-02-20 04:45:22 +00001022 // A is "considered to be at least as specialized" as P iff deduction
1023 // succeeds, so we model this as a deduction failure. Note that
1024 // [the first type] is P and [the other type] is A here; the standard
1025 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001026 Qualifiers ParamQuals = Param.getQualifiers();
1027 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001028 if ((ParamRef->isLValueReferenceType() &&
1029 !ArgRef->isLValueReferenceType()) ||
1030 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1031 (ParamQuals.hasNonTrivialObjCLifetime() &&
1032 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1033 ParamQuals.withoutObjCLifetime() ==
1034 ArgQuals.withoutObjCLifetime())) {
1035 Info.FirstArg = TemplateArgument(ParamIn);
1036 Info.SecondArg = TemplateArgument(ArgIn);
1037 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001038 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040
Richard Smithed563c22015-02-20 04:45:22 +00001041 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001042 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 // version of P.
1045 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001047 // version of A.
1048 Arg = Arg.getUnqualifiedType();
1049 } else {
1050 // C++0x [temp.deduct.call]p4 bullet 1:
1051 // - If the original P is a reference type, the deduced A (i.e., the type
1052 // referred to by the reference) can be more cv-qualified than the
1053 // transformed A.
1054 if (TDF & TDF_ParamWithReferenceType) {
1055 Qualifiers Quals;
1056 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1057 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001058 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001059 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Douglas Gregor85f240c2011-01-25 17:19:08 +00001062 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1063 // C++0x [temp.deduct.type]p10:
1064 // If P and A are function types that originated from deduction when
1065 // taking the address of a function template (14.8.2.2) or when deducing
1066 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067 // Ai are parameters of the top-level parameter-type-list of P and A,
1068 // respectively, Pi is adjusted if it is an rvalue reference to a
1069 // cv-unqualified template parameter and Ai is an lvalue reference, in
1070 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001071 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1072 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001073 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001074 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075
Douglas Gregor85f240c2011-01-25 17:19:08 +00001076 if (const RValueReferenceType *ParamRef
1077 = Param->getAs<RValueReferenceType>()) {
1078 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1079 !ParamRef->getPointeeType().getQualifiers())
1080 if (Arg->isLValueReferenceType())
1081 Param = ParamRef->getPointeeType();
1082 }
1083 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001086 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001087 // A template type argument T, a template template argument TT or a
1088 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001089 // the following forms:
1090 //
1091 // T
1092 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001093 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001094 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001095 // Just skip any attempts to deduce from a placeholder type or a parameter
1096 // at a different depth.
1097 if (Arg->isPlaceholderType() ||
1098 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001099 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001100
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001101 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001102 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001103
Douglas Gregor60454822009-07-22 20:02:25 +00001104 // If the argument type is an array type, move the qualifiers up to the
1105 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001106 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001107 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001108 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001109 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001110 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001111 RecanonicalizeArg = true;
1112 }
1113 }
Mike Stump11289f42009-09-09 15:08:12 +00001114
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001115 // The argument type can not be less qualified than the parameter
1116 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001117 if (!(TDF & TDF_IgnoreQualifiers) &&
1118 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001119 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001120 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001121 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001122 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001123 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001124
Richard Smith87d263e2016-12-25 08:05:23 +00001125 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1126 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001127 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001128 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001129
Douglas Gregor1d684c22011-04-28 00:56:09 +00001130 // Remove any qualifiers on the parameter from the deduced type.
1131 // We checked the qualifiers for consistency above.
1132 Qualifiers DeducedQs = DeducedType.getQualifiers();
1133 Qualifiers ParamQs = Param.getQualifiers();
1134 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1135 if (ParamQs.hasObjCGCAttr())
1136 DeducedQs.removeObjCGCAttr();
1137 if (ParamQs.hasAddressSpace())
1138 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001139 if (ParamQs.hasObjCLifetime())
1140 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001141
Douglas Gregore46db902011-06-17 22:11:49 +00001142 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001143 // If template deduction would produce a lifetime qualifier on a type
1144 // that is not a lifetime type, template argument deduction fails.
1145 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1146 !DeducedType->isDependentType()) {
1147 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1148 Info.FirstArg = TemplateArgument(Param);
1149 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001150 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001151 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001152
Douglas Gregora4f2b432011-07-26 14:53:44 +00001153 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001154 // If template deduction would produce an argument type with lifetime type
1155 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001156 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001157 DeducedType->isObjCLifetimeType() &&
1158 !DeducedQs.hasObjCLifetime())
1159 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001160
Douglas Gregor1d684c22011-04-28 00:56:09 +00001161 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1162 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001163
Douglas Gregord6605db2009-07-22 21:30:48 +00001164 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001165 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001166
Richard Smith5f274382016-09-28 23:55:27 +00001167 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001169 Deduced[Index],
1170 NewDeduced);
1171 if (Result.isNull()) {
1172 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1173 Info.FirstArg = Deduced[Index];
1174 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001178 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001180 }
1181
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001182 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001183 Info.FirstArg = TemplateArgument(ParamIn);
1184 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001185
Douglas Gregorfb322d82011-01-14 05:11:40 +00001186 // If the parameter is an already-substituted template parameter
1187 // pack, do nothing: we don't know which of its arguments to look
1188 // at, so we have to wait until all of the parameter packs in this
1189 // expansion have arguments.
1190 if (isa<SubstTemplateTypeParmPackType>(Param))
1191 return Sema::TDK_Success;
1192
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001193 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001194 CanQualType CanParam = S.Context.getCanonicalType(Param);
1195 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001196 if (!(TDF & TDF_IgnoreQualifiers)) {
1197 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001198 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001199 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001200 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001201 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001202 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001204
Douglas Gregor194ea692012-03-11 03:29:50 +00001205 // If the parameter type is not dependent, there is nothing to deduce.
1206 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001207 if (!(TDF & TDF_SkipNonDependent)) {
1208 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1209 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1210 Param != Arg;
1211 if (NonDeduced) {
1212 return Sema::TDK_NonDeducedMismatch;
1213 }
1214 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001215 return Sema::TDK_Success;
1216 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001217 } else if (!Param->isDependentType()) {
1218 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1219 ArgUnqualType = CanArg.getUnqualifiedType();
1220 bool Success = (TDF & TDF_InOverloadResolution)?
1221 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1222 ArgUnqualType) :
1223 ParamUnqualType == ArgUnqualType;
1224 if (Success)
1225 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001226 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001227
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001228 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001229 // Non-canonical types cannot appear here.
1230#define NON_CANONICAL_TYPE(Class, Base) \
1231 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1232#define TYPE(Class, Base)
1233#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001234
Douglas Gregor39c02722011-06-15 16:02:29 +00001235 case Type::TemplateTypeParm:
1236 case Type::SubstTemplateTypeParmPack:
1237 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001238
1239 // These types cannot be dependent, so simply check whether the types are
1240 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001241 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001242 case Type::VariableArray:
1243 case Type::Vector:
1244 case Type::FunctionNoProto:
1245 case Type::Record:
1246 case Type::Enum:
1247 case Type::ObjCObject:
1248 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001249 case Type::ObjCObjectPointer: {
1250 if (TDF & TDF_SkipNonDependent)
1251 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001252
Douglas Gregor194ea692012-03-11 03:29:50 +00001253 if (TDF & TDF_IgnoreQualifiers) {
1254 Param = Param.getUnqualifiedType();
1255 Arg = Arg.getUnqualifiedType();
1256 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001257
Douglas Gregor194ea692012-03-11 03:29:50 +00001258 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1259 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001260
1261 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001262 case Type::Complex:
1263 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001264 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1265 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001266 ComplexArg->getElementType(),
1267 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001268
1269 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001270
1271 // _Atomic T [extension]
1272 case Type::Atomic:
1273 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001274 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001275 cast<AtomicType>(Param)->getValueType(),
1276 AtomicArg->getValueType(),
1277 Info, Deduced, TDF);
1278
1279 return Sema::TDK_NonDeducedMismatch;
1280
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001281 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001282 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001283 QualType PointeeType;
1284 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1285 PointeeType = PointerArg->getPointeeType();
1286 } else if (const ObjCObjectPointerType *PointerArg
1287 = Arg->getAs<ObjCObjectPointerType>()) {
1288 PointeeType = PointerArg->getPointeeType();
1289 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001290 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregorfc516c92009-06-26 23:27:24 +00001293 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001294 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1295 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001296 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001297 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001300 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001301 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001302 const LValueReferenceType *ReferenceArg =
1303 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001304 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001305 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001307 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001308 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001309 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001310 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001311
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001312 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001313 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001314 const RValueReferenceType *ReferenceArg =
1315 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001316 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001317 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001318
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001319 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1320 cast<RValueReferenceType>(Param)->getPointeeType(),
1321 ReferenceArg->getPointeeType(),
1322 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001325 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001326 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001327 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001328 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001329 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001330 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001331
John McCallf7332682010-08-19 00:20:19 +00001332 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001333 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1334 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1335 IncompleteArrayArg->getElementType(),
1336 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001337 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001338
1339 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001340 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001341 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001342 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001343 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001344 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001345
1346 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001347 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001348 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001349 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001350
John McCallf7332682010-08-19 00:20:19 +00001351 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001352 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1353 ConstantArrayParm->getElementType(),
1354 ConstantArrayArg->getElementType(),
1355 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001356 }
1357
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001358 // type [i]
1359 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001360 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001361 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001362 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001363
John McCallf7332682010-08-19 00:20:19 +00001364 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1365
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001366 // Check the element type of the arrays
1367 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001368 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001369 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001370 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1371 DependentArrayParm->getElementType(),
1372 ArrayArg->getElementType(),
1373 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001374 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001376 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001377 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001378 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001379 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001380 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001381
1382 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001383 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001384 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1385 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001386 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001387 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1388 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001389 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001390 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001391 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001392 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001393 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001394 if (const DependentSizedArrayType *DependentArrayArg
1395 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001396 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001397 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001398 DependentArrayArg->getSizeExpr(),
1399 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001400
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001402 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
1405 // type(*)(T)
1406 // T(*)()
1407 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001408 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001409 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001410 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001411 dyn_cast<FunctionProtoType>(Arg);
1412 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001413 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001414
1415 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001416 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001417
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001419 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001421 != FunctionProtoArg->getRefQualifier() ||
1422 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001423 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001424
Anders Carlsson2128ec72009-06-08 15:19:08 +00001425 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001426 if (Sema::TemplateDeductionResult Result =
1427 DeduceTemplateArgumentsByTypeMatch(
1428 S, TemplateParams, FunctionProtoParam->getReturnType(),
1429 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001430 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001431
Alp Toker9cacbab2014-01-20 20:26:09 +00001432 return DeduceTemplateArguments(
1433 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1434 FunctionProtoParam->getNumParams(),
1435 FunctionProtoArg->param_type_begin(),
1436 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001437 }
Mike Stump11289f42009-09-09 15:08:12 +00001438
John McCalle78aac42010-03-10 03:28:59 +00001439 case Type::InjectedClassName: {
1440 // Treat a template's injected-class-name as if the template
1441 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001442 Param = cast<InjectedClassNameType>(Param)
1443 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001444 assert(isa<TemplateSpecializationType>(Param) &&
1445 "injected class name is not a template specialization type");
1446 // fall through
1447 }
1448
Douglas Gregor705c9002009-06-26 20:57:09 +00001449 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001450 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001451 // TT<T>
1452 // TT<i>
1453 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001454 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001455 const TemplateSpecializationType *SpecParam =
1456 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001457
Richard Smith9b296e32016-04-25 19:09:05 +00001458 // When Arg cannot be a derived class, we can just try to deduce template
1459 // arguments from the template-id.
1460 const RecordType *RecordT = Arg->getAs<RecordType>();
1461 if (!(TDF & TDF_DerivedClass) || !RecordT)
1462 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1463 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Richard Smith9b296e32016-04-25 19:09:05 +00001465 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1466 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001467
Richard Smith9b296e32016-04-25 19:09:05 +00001468 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1469 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Richard Smith9b296e32016-04-25 19:09:05 +00001471 if (Result == Sema::TDK_Success)
1472 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001473
Richard Smith9b296e32016-04-25 19:09:05 +00001474 // We cannot inspect base classes as part of deduction when the type
1475 // is incomplete, so either instantiate any templates necessary to
1476 // complete the type, or skip over it if it cannot be completed.
1477 if (!S.isCompleteType(Info.getLocation(), Arg))
1478 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001479
Richard Smith9b296e32016-04-25 19:09:05 +00001480 // C++14 [temp.deduct.call] p4b3:
1481 // If P is a class and P has the form simple-template-id, then the
1482 // transformed A can be a derived class of the deduced A. Likewise if
1483 // P is a pointer to a class of the form simple-template-id, the
1484 // transformed A can be a pointer to a derived class pointed to by the
1485 // deduced A.
1486 //
1487 // These alternatives are considered only if type deduction would
1488 // otherwise fail. If they yield more than one possible deduced A, the
1489 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001490
Faisal Vali683b0742016-05-19 02:28:21 +00001491 // Reset the incorrectly deduced argument from above.
1492 Deduced = DeducedOrig;
1493
1494 // Use data recursion to crawl through the list of base classes.
1495 // Visited contains the set of nodes we have already visited, while
1496 // ToVisit is our stack of records that we still need to visit.
1497 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1498 SmallVector<const RecordType *, 8> ToVisit;
1499 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001500 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001501 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001502 while (!ToVisit.empty()) {
1503 // Retrieve the next class in the inheritance hierarchy.
1504 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001505
Faisal Vali683b0742016-05-19 02:28:21 +00001506 // If we have already seen this type, skip it.
1507 if (!Visited.insert(NextT).second)
1508 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001509
Faisal Vali683b0742016-05-19 02:28:21 +00001510 // If this is a base class, try to perform template argument
1511 // deduction from it.
1512 if (NextT != RecordT) {
1513 TemplateDeductionInfo BaseInfo(Info.getLocation());
1514 Sema::TemplateDeductionResult BaseResult =
1515 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1516 QualType(NextT, 0), BaseInfo, Deduced);
1517
1518 // If template argument deduction for this base was successful,
1519 // note that we had some success. Otherwise, ignore any deductions
1520 // from this base class.
1521 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001522 // If we've already seen some success, then deduction fails due to
1523 // an ambiguity (temp.deduct.call p5).
1524 if (Successful)
1525 return Sema::TDK_MiscellaneousDeductionFailure;
1526
Faisal Vali683b0742016-05-19 02:28:21 +00001527 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001528 std::swap(SuccessfulDeduced, Deduced);
1529
Faisal Vali683b0742016-05-19 02:28:21 +00001530 Info.Param = BaseInfo.Param;
1531 Info.FirstArg = BaseInfo.FirstArg;
1532 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001533 }
1534
1535 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Faisal Vali683b0742016-05-19 02:28:21 +00001538 // Visit base classes
1539 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1540 for (const auto &Base : Next->bases()) {
1541 assert(Base.getType()->isRecordType() &&
1542 "Base class that isn't a record?");
1543 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1544 }
1545 }
Mike Stump11289f42009-09-09 15:08:12 +00001546
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001547 if (Successful) {
1548 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001549 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001550 }
Richard Smith9b296e32016-04-25 19:09:05 +00001551
Douglas Gregore81f3e72009-07-07 23:09:34 +00001552 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001553 }
1554
Douglas Gregor637d9982009-06-10 23:47:09 +00001555 // T type::*
1556 // T T::*
1557 // T (type::*)()
1558 // type (T::*)()
1559 // type (type::*)(T)
1560 // type (T::*)(T)
1561 // T (type::*)(T)
1562 // T (T::*)()
1563 // T (T::*)(T)
1564 case Type::MemberPointer: {
1565 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1566 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1567 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001568 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001569
David Majnemera381cda2015-11-30 20:34:28 +00001570 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1571 if (ParamPointeeType->isFunctionType())
1572 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1573 /*IsCtorOrDtor=*/false, Info.getLocation());
1574 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1575 if (ArgPointeeType->isFunctionType())
1576 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1577 /*IsCtorOrDtor=*/false, Info.getLocation());
1578
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001579 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001580 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001581 ParamPointeeType,
1582 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001583 Info, Deduced,
1584 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001585 return Result;
1586
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001587 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1588 QualType(MemPtrParam->getClass(), 0),
1589 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001590 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001591 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001592 }
1593
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001594 // (clang extension)
1595 //
Mike Stump11289f42009-09-09 15:08:12 +00001596 // type(^)(T)
1597 // T(^)()
1598 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001599 case Type::BlockPointer: {
1600 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1601 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001602
Anders Carlssona767eee2009-06-12 16:23:10 +00001603 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001604 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001605
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001606 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1607 BlockPtrParam->getPointeeType(),
1608 BlockPtrArg->getPointeeType(),
1609 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001610 }
1611
Douglas Gregor39c02722011-06-15 16:02:29 +00001612 // (clang extension)
1613 //
1614 // T __attribute__(((ext_vector_type(<integral constant>))))
1615 case Type::ExtVector: {
1616 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1617 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1618 // Make sure that the vectors have the same number of elements.
1619 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1620 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001621
Douglas Gregor39c02722011-06-15 16:02:29 +00001622 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001623 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1624 VectorParam->getElementType(),
1625 VectorArg->getElementType(),
1626 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001627 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001628
1629 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001630 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1631 // We can't check the number of elements, since the argument has a
1632 // dependent number of elements. This can only occur during partial
1633 // ordering.
1634
1635 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001636 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1637 VectorParam->getElementType(),
1638 VectorArg->getElementType(),
1639 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001640 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001641
Douglas Gregor39c02722011-06-15 16:02:29 +00001642 return Sema::TDK_NonDeducedMismatch;
1643 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001644
Douglas Gregor39c02722011-06-15 16:02:29 +00001645 // (clang extension)
1646 //
1647 // T __attribute__(((ext_vector_type(N))))
1648 case Type::DependentSizedExtVector: {
1649 const DependentSizedExtVectorType *VectorParam
1650 = cast<DependentSizedExtVectorType>(Param);
1651
1652 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1653 // Perform deduction on the element types.
1654 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001655 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1656 VectorParam->getElementType(),
1657 VectorArg->getElementType(),
1658 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001659 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001660
Douglas Gregor39c02722011-06-15 16:02:29 +00001661 // Perform deduction on the vector size, if we can.
1662 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001663 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001664 if (!NTTP)
1665 return Sema::TDK_Success;
1666
1667 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1668 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001669 // Note that we use the "array bound" rules here; just like in that
1670 // case, we don't have any particular type for the vector size, but
1671 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001672 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001673 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001674 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001675 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001676
1677 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001678 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1679 // Perform deduction on the element types.
1680 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001681 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1682 VectorParam->getElementType(),
1683 VectorArg->getElementType(),
1684 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001685 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001686
Douglas Gregor39c02722011-06-15 16:02:29 +00001687 // Perform deduction on the vector size, if we can.
1688 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001689 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001690 if (!NTTP)
1691 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001692
Richard Smith5f274382016-09-28 23:55:27 +00001693 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1694 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001695 Info, Deduced);
1696 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001697
Douglas Gregor39c02722011-06-15 16:02:29 +00001698 return Sema::TDK_NonDeducedMismatch;
1699 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001700
Douglas Gregor637d9982009-06-10 23:47:09 +00001701 case Type::TypeOfExpr:
1702 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001703 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001704 case Type::UnresolvedUsing:
1705 case Type::Decltype:
1706 case Type::UnaryTransform:
1707 case Type::Auto:
1708 case Type::DependentTemplateSpecialization:
1709 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001710 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001711 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001712 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001713 }
1714
David Blaikiee4d798f2012-01-20 21:50:17 +00001715 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001716}
1717
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001718static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001719DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001720 TemplateParameterList *TemplateParams,
1721 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001722 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001723 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001724 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001725 // If the template argument is a pack expansion, perform template argument
1726 // deduction against the pattern of that expansion. This only occurs during
1727 // partial ordering.
1728 if (Arg.isPackExpansion())
1729 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001731 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001732 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001733 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001734
1735 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001736 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001737 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1738 Param.getAsType(),
1739 Arg.getAsType(),
1740 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001741 Info.FirstArg = Param;
1742 Info.SecondArg = Arg;
1743 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001744
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001746 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001748 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001749 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001750 Info.FirstArg = Param;
1751 Info.SecondArg = Arg;
1752 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001753
1754 case TemplateArgument::TemplateExpansion:
1755 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001757 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001758 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001759 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001760 return Sema::TDK_Success;
1761
1762 Info.FirstArg = Param;
1763 Info.SecondArg = Arg;
1764 return Sema::TDK_NonDeducedMismatch;
1765
1766 case TemplateArgument::NullPtr:
1767 if (Arg.getKind() == TemplateArgument::NullPtr &&
1768 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001769 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001771 Info.FirstArg = Param;
1772 Info.SecondArg = Arg;
1773 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001774
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001775 case TemplateArgument::Integral:
1776 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001777 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001778 return Sema::TDK_Success;
1779
1780 Info.FirstArg = Param;
1781 Info.SecondArg = Arg;
1782 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001783 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001784
1785 if (Arg.getKind() == TemplateArgument::Expression) {
1786 Info.FirstArg = Param;
1787 Info.SecondArg = Arg;
1788 return Sema::TDK_NonDeducedMismatch;
1789 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001790
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001791 Info.FirstArg = Param;
1792 Info.SecondArg = Arg;
1793 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001794
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001795 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001796 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001797 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001798 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001799 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001800 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001801 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001802 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001803 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001804 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001805 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1806 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001807 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001808 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001809 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1810 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001811 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001812 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1813 Arg.getAsDecl(),
1814 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001815 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001817 Info.FirstArg = Param;
1818 Info.SecondArg = Arg;
1819 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001820 }
Mike Stump11289f42009-09-09 15:08:12 +00001821
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001822 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001823 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001824 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001825 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001826 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
David Blaikiee4d798f2012-01-20 21:50:17 +00001829 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001830}
1831
Douglas Gregor7baabef2010-12-22 18:17:10 +00001832/// \brief Determine whether there is a template argument to be used for
1833/// deduction.
1834///
1835/// This routine "expands" argument packs in-place, overriding its input
1836/// parameters so that \c Args[ArgIdx] will be the available template argument.
1837///
1838/// \returns true if there is another template argument (which will be at
1839/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001840static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1841 unsigned &ArgIdx) {
1842 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001843 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Douglas Gregor7baabef2010-12-22 18:17:10 +00001845 const TemplateArgument &Arg = Args[ArgIdx];
1846 if (Arg.getKind() != TemplateArgument::Pack)
1847 return true;
1848
Richard Smith0bda5b52016-12-23 23:46:56 +00001849 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1850 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001851 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001852 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001853}
1854
Douglas Gregord0ad2942010-12-23 01:24:45 +00001855/// \brief Determine whether the given set of template arguments has a pack
1856/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001857static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1858 bool FoundPackExpansion = false;
1859 for (const auto &A : Args) {
1860 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001861 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001862
1863 if (A.getKind() == TemplateArgument::Pack)
1864 return hasPackExpansionBeforeEnd(A.pack_elements());
1865
1866 if (A.isPackExpansion())
1867 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869
Douglas Gregord0ad2942010-12-23 01:24:45 +00001870 return false;
1871}
1872
Douglas Gregor7baabef2010-12-22 18:17:10 +00001873static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001874DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001875 ArrayRef<TemplateArgument> Params,
1876 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001877 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001878 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1879 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001880 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881 // If the template argument list of P contains a pack expansion that is not
1882 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001883 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001884 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001885 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888 // If P has a form that contains <T> or <i>, then each argument Pi of the
1889 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001890 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001891 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001892 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001893 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregor7baabef2010-12-22 18:17:10 +00001896 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001897 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001898 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1899 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900
Richard Smith26b86ea2016-12-31 21:41:23 +00001901 // C++1z [temp.deduct.type]p9:
1902 // During partial ordering, if Ai was originally a pack expansion [and]
1903 // Pi is not a pack expansion, template argument deduction fails.
1904 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001905 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001907 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001908 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001909 = DeduceTemplateArguments(S, TemplateParams,
1910 Params[ParamIdx], Args[ArgIdx],
1911 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912 return Result;
1913
Douglas Gregor7baabef2010-12-22 18:17:10 +00001914 // Move to the next argument.
1915 ++ArgIdx;
1916 continue;
1917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001919 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001921 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 // If Pi is a pack expansion, then the pattern of Pi is compared with
1923 // each remaining argument in the template argument list of A. Each
1924 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 // template parameter packs expanded by Pi.
1926 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001928 // FIXME: If there are no remaining arguments, we can bail out early
1929 // and set any deduced parameter packs to an empty argument pack.
1930 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931
Richard Smith0a80d572014-05-29 01:12:14 +00001932 // Prepare to deduce the packs within the pattern.
1933 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934
1935 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001937 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001938 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001939 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001940 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001942 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001944 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1945 Info, Deduced))
1946 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
Richard Smith0a80d572014-05-29 01:12:14 +00001948 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 // Build argument packs for each of the parameter packs expanded by this
1952 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001953 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
Douglas Gregor7baabef2010-12-22 18:17:10 +00001957 return Sema::TDK_Success;
1958}
1959
Mike Stump11289f42009-09-09 15:08:12 +00001960static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001961DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001962 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001963 const TemplateArgumentList &ParamList,
1964 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001965 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001966 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001967 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00001968 ArgList.asArray(), Info, Deduced,
1969 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001970}
1971
Douglas Gregor705c9002009-06-26 20:57:09 +00001972/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001973static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00001974 TemplateArgument X,
1975 const TemplateArgument &Y,
1976 bool PackExpansionMatchesPack = false) {
1977 // If we're checking deduced arguments (X) against original arguments (Y),
1978 // we will have flattened packs to non-expansions in X.
1979 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1980 X = X.getPackExpansionPattern();
1981
Douglas Gregor705c9002009-06-26 20:57:09 +00001982 if (X.getKind() != Y.getKind())
1983 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001984
Douglas Gregor705c9002009-06-26 20:57:09 +00001985 switch (X.getKind()) {
1986 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001987 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregor705c9002009-06-26 20:57:09 +00001989 case TemplateArgument::Type:
1990 return Context.getCanonicalType(X.getAsType()) ==
1991 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001992
Douglas Gregor705c9002009-06-26 20:57:09 +00001993 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001994 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001995
1996 case TemplateArgument::NullPtr:
1997 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001998
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001999 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002000 case TemplateArgument::TemplateExpansion:
2001 return Context.getCanonicalTemplateName(
2002 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2003 Context.getCanonicalTemplateName(
2004 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
Douglas Gregor705c9002009-06-26 20:57:09 +00002006 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002007 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002009 case TemplateArgument::Expression: {
2010 llvm::FoldingSetNodeID XID, YID;
2011 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002013 return XID == YID;
2014 }
Mike Stump11289f42009-09-09 15:08:12 +00002015
Douglas Gregor705c9002009-06-26 20:57:09 +00002016 case TemplateArgument::Pack:
2017 if (X.pack_size() != Y.pack_size())
2018 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002019
2020 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2021 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002022 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002023 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002024 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002025 return false;
2026
2027 return true;
2028 }
2029
David Blaikiee4d798f2012-01-20 21:50:17 +00002030 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002031}
2032
Douglas Gregorca4686d2011-01-04 23:35:54 +00002033/// \brief Allocate a TemplateArgumentLoc where all locations have
2034/// been initialized to the given location.
2035///
James Dennett634962f2012-06-14 21:40:34 +00002036/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002037/// location information for.
2038///
2039/// \param NTTPType For a declaration template argument, the type of
2040/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002041/// argument. Can be null if no type sugar is available to add to the
2042/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002043///
2044/// \param Loc The source location to use for the resulting template
2045/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002046TemplateArgumentLoc
2047Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2048 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049 switch (Arg.getKind()) {
2050 case TemplateArgument::Null:
2051 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Douglas Gregorca4686d2011-01-04 23:35:54 +00002053 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002054 return TemplateArgumentLoc(
2055 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
Douglas Gregorca4686d2011-01-04 23:35:54 +00002057 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002058 if (NTTPType.isNull())
2059 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002060 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2061 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002062 return TemplateArgumentLoc(TemplateArgument(E), E);
2063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002064
Eli Friedmanb826a002012-09-26 02:36:12 +00002065 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002066 if (NTTPType.isNull())
2067 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002068 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2069 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002070 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2071 E);
2072 }
2073
Douglas Gregorca4686d2011-01-04 23:35:54 +00002074 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002075 Expr *E =
2076 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002077 return TemplateArgumentLoc(TemplateArgument(E), E);
2078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Douglas Gregor9d802122011-03-02 17:09:35 +00002080 case TemplateArgument::Template:
2081 case TemplateArgument::TemplateExpansion: {
2082 NestedNameSpecifierLocBuilder Builder;
2083 TemplateName Template = Arg.getAsTemplate();
2084 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002085 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002086 else if (QualifiedTemplateName *QTN =
2087 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002088 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002089
Douglas Gregor9d802122011-03-02 17:09:35 +00002090 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002091 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002092 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002093
2094 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002095 Loc, Loc);
2096 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002097
Douglas Gregorca4686d2011-01-04 23:35:54 +00002098 case TemplateArgument::Expression:
2099 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
Douglas Gregorca4686d2011-01-04 23:35:54 +00002101 case TemplateArgument::Pack:
2102 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104
David Blaikiee4d798f2012-01-20 21:50:17 +00002105 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002106}
2107
2108
2109/// \brief Convert the given deduced template argument and add it to the set of
2110/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002111static bool
2112ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2113 DeducedTemplateArgument Arg,
2114 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002115 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002116 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002117 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002118 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2119 unsigned ArgumentPackIndex) {
2120 // Convert the deduced template argument into a template
2121 // argument that we can check, almost as if the user had written
2122 // the template argument explicitly.
2123 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002124 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002125
2126 // Check the template argument, converting it as necessary.
2127 return S.CheckTemplateArgument(
2128 Param, ArgLoc, Template, Template->getLocation(),
2129 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002130 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002131 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2132 : Sema::CTAK_Deduced)
2133 : Sema::CTAK_Specified);
2134 };
2135
Douglas Gregorca4686d2011-01-04 23:35:54 +00002136 if (Arg.getKind() == TemplateArgument::Pack) {
2137 // This is a template argument pack, so check each of its arguments against
2138 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002139 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002140 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002141 // When converting the deduced template argument, append it to the
2142 // general output list. We need to do this so that the template argument
2143 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002144 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002145 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002146 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2147 "deduced nested pack");
2148 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150
Douglas Gregor51bc5712011-01-05 20:52:18 +00002151 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002152 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Richard Smithdf18ee92016-02-03 20:40:30 +00002155 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002156 // itself, in case that substitution fails.
2157 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002158 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002159 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002160 MultiLevelTemplateArgumentList Args(TemplateArgs);
2161
2162 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2163 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2164 NTTP, Output,
2165 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002166 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002167 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2168 NTTP->getDeclName()).isNull())
2169 return true;
2170 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2171 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2172 TTP, Output,
2173 Template->getSourceRange());
2174 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2175 return true;
2176 }
2177 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002178 }
Richard Smith37acb792016-02-03 20:15:01 +00002179
Douglas Gregorca4686d2011-01-04 23:35:54 +00002180 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002181 Output.push_back(
2182 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002183 return false;
2184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185
Richard Smith37acb792016-02-03 20:15:01 +00002186 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002187}
2188
Richard Smith1f5be4d2016-12-21 01:10:31 +00002189// FIXME: This should not be a template, but
2190// ClassTemplatePartialSpecializationDecl sadly does not derive from
2191// TemplateDecl.
2192template<typename TemplateDeclT>
2193static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002194 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002195 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2196 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2197 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2198 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2199 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2200
2201 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2202 NamedDecl *Param = TemplateParams->getParam(I);
2203
2204 if (!Deduced[I].isNull()) {
2205 if (I < NumAlreadyConverted) {
2206 // We have already fully type-checked and converted this
2207 // argument, because it was explicitly-specified. Just record the
2208 // presence of this argument.
2209 Builder.push_back(Deduced[I]);
2210 // We may have had explicitly-specified template arguments for a
2211 // template parameter pack (that may or may not have been extended
2212 // via additional deduced arguments).
2213 if (Param->isParameterPack() && CurrentInstantiationScope) {
2214 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2215 Param) {
2216 // Forget the partially-substituted pack; its substitution is now
2217 // complete.
2218 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2219 }
2220 }
2221 continue;
2222 }
2223
2224 // We have deduced this argument, so it still needs to be
2225 // checked and converted.
2226 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002227 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002228 Info.Param = makeTemplateParameter(Param);
2229 // FIXME: These template arguments are temporary. Free them!
2230 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2231 return Sema::TDK_SubstitutionFailure;
2232 }
2233
2234 continue;
2235 }
2236
2237 // C++0x [temp.arg.explicit]p3:
2238 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2239 // be deduced to an empty sequence of template arguments.
2240 // FIXME: Where did the word "trailing" come from?
2241 if (Param->isTemplateParameterPack()) {
2242 // We may have had explicitly-specified template arguments for this
2243 // template parameter pack. If so, our empty deduction extends the
2244 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2245 const TemplateArgument *ExplicitArgs;
2246 unsigned NumExplicitArgs;
2247 if (CurrentInstantiationScope &&
2248 CurrentInstantiationScope->getPartiallySubstitutedPack(
2249 &ExplicitArgs, &NumExplicitArgs) == Param) {
2250 Builder.push_back(TemplateArgument(
2251 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2252
2253 // Forget the partially-substituted pack; its substitution is now
2254 // complete.
2255 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2256 } else {
2257 // Go through the motions of checking the empty argument pack against
2258 // the parameter pack.
2259 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002260 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2261 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002262 Info.Param = makeTemplateParameter(Param);
2263 // FIXME: These template arguments are temporary. Free them!
2264 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2265 return Sema::TDK_SubstitutionFailure;
2266 }
2267 }
2268 continue;
2269 }
2270
2271 // Substitute into the default template argument, if available.
2272 bool HasDefaultArg = false;
2273 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2274 if (!TD) {
2275 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2276 return Sema::TDK_Incomplete;
2277 }
2278
2279 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2280 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2281 HasDefaultArg);
2282
2283 // If there was no default argument, deduction is incomplete.
2284 if (DefArg.getArgument().isNull()) {
2285 Info.Param = makeTemplateParameter(
2286 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2287 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2288 if (PartialOverloading) break;
2289
2290 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2291 : Sema::TDK_Incomplete;
2292 }
2293
2294 // Check whether we can actually use the default argument.
2295 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2296 TD->getSourceRange().getEnd(), 0, Builder,
2297 Sema::CTAK_Specified)) {
2298 Info.Param = makeTemplateParameter(
2299 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2300 // FIXME: These template arguments are temporary. Free them!
2301 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2302 return Sema::TDK_SubstitutionFailure;
2303 }
2304
2305 // If we get here, we successfully used the default template argument.
2306 }
2307
2308 return Sema::TDK_Success;
2309}
2310
Richard Smith0da6dc42016-12-24 16:40:51 +00002311DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2312 if (auto *DC = dyn_cast<DeclContext>(D))
2313 return DC;
2314 return D->getDeclContext();
2315}
2316
2317template<typename T> struct IsPartialSpecialization {
2318 static constexpr bool value = false;
2319};
2320template<>
2321struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2322 static constexpr bool value = true;
2323};
2324template<>
2325struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2326 static constexpr bool value = true;
2327};
2328
2329/// Complete template argument deduction for a partial specialization.
2330template <typename T>
2331static typename std::enable_if<IsPartialSpecialization<T>::value,
2332 Sema::TemplateDeductionResult>::type
2333FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002334 Sema &S, T *Partial, bool IsPartialOrdering,
2335 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002336 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2337 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002338 // Unevaluated SFINAE context.
2339 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002340 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002341
Richard Smith0da6dc42016-12-24 16:40:51 +00002342 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002343
2344 // C++ [temp.deduct.type]p2:
2345 // [...] or if any template argument remains neither deduced nor
2346 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002347 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002348 if (auto Result = ConvertDeducedTemplateArguments(
2349 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002350 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002351
Douglas Gregor684268d2010-04-29 06:21:43 +00002352 // Form the template argument list from the deduced template arguments.
2353 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002354 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002355
Douglas Gregor684268d2010-04-29 06:21:43 +00002356 Info.reset(DeducedArgumentList);
2357
2358 // Substitute the deduced template arguments into the template
2359 // arguments of the class template partial specialization, and
2360 // verify that the instantiated template arguments are both valid
2361 // and are equivalent to the template arguments originally provided
2362 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002363 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002364 auto *Template = Partial->getSpecializedTemplate();
2365 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2366 Partial->getTemplateArgsAsWritten();
2367 const TemplateArgumentLoc *PartialTemplateArgs =
2368 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002369
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002370 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2371 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002372
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002373 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002374 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2375 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2376 if (ParamIdx >= Partial->getTemplateParameters()->size())
2377 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2378
Richard Smith0da6dc42016-12-24 16:40:51 +00002379 Decl *Param = const_cast<NamedDecl *>(
2380 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002381 Info.Param = makeTemplateParameter(Param);
2382 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2383 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002384 }
2385
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002386 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002387 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2388 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002389 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002390
Richard Smith0da6dc42016-12-24 16:40:51 +00002391 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002392 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002393 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002394 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002395 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002396 Info.FirstArg = TemplateArgs[I];
2397 Info.SecondArg = InstArg;
2398 return Sema::TDK_NonDeducedMismatch;
2399 }
2400 }
2401
2402 if (Trap.hasErrorOccurred())
2403 return Sema::TDK_SubstitutionFailure;
2404
2405 return Sema::TDK_Success;
2406}
2407
Richard Smith0e617ec2016-12-27 07:56:27 +00002408/// Complete template argument deduction for a class or variable template,
2409/// when partial ordering against a partial specialization.
2410// FIXME: Factor out duplication with partial specialization version above.
2411Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2412 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2413 const TemplateArgumentList &TemplateArgs,
2414 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2415 TemplateDeductionInfo &Info) {
2416 // Unevaluated SFINAE context.
2417 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2418 Sema::SFINAETrap Trap(S);
2419
2420 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2421
2422 // C++ [temp.deduct.type]p2:
2423 // [...] or if any template argument remains neither deduced nor
2424 // explicitly specified, template argument deduction fails.
2425 SmallVector<TemplateArgument, 4> Builder;
2426 if (auto Result = ConvertDeducedTemplateArguments(
2427 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2428 return Result;
2429
2430 // Check that we produced the correct argument list.
2431 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2432 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2433 TemplateArgument InstArg = Builder[I];
2434 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2435 /*PackExpansionMatchesPack*/true)) {
2436 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2437 Info.FirstArg = TemplateArgs[I];
2438 Info.SecondArg = InstArg;
2439 return Sema::TDK_NonDeducedMismatch;
2440 }
2441 }
2442
2443 if (Trap.hasErrorOccurred())
2444 return Sema::TDK_SubstitutionFailure;
2445
2446 return Sema::TDK_Success;
2447}
2448
2449
Douglas Gregor170bc422009-06-12 22:31:52 +00002450/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002451/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002452/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002453Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002454Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002455 const TemplateArgumentList &TemplateArgs,
2456 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002457 if (Partial->isInvalidDecl())
2458 return TDK_Invalid;
2459
Douglas Gregor170bc422009-06-12 22:31:52 +00002460 // C++ [temp.class.spec.match]p2:
2461 // A partial specialization matches a given actual template
2462 // argument list if the template arguments of the partial
2463 // specialization can be deduced from the actual template argument
2464 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002465
2466 // Unevaluated SFINAE context.
2467 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002468 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002469
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002470 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002471 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002472 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002473 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002474 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002475 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002476 TemplateArgs, Info, Deduced))
2477 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002478
Richard Smith80934652012-07-16 01:09:10 +00002479 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002480 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2481 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002482 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002483 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002484
Douglas Gregore1416332009-06-14 08:02:22 +00002485 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002486 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002487
Richard Smith87d263e2016-12-25 08:05:23 +00002488 return ::FinishTemplateArgumentDeduction(
2489 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002490}
Douglas Gregor91772d12009-06-13 00:26:55 +00002491
Larisse Voufo39a1e502013-08-06 01:03:05 +00002492/// \brief Perform template argument deduction to determine whether
2493/// the given template arguments match the given variable template
2494/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002495Sema::TemplateDeductionResult
2496Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2497 const TemplateArgumentList &TemplateArgs,
2498 TemplateDeductionInfo &Info) {
2499 if (Partial->isInvalidDecl())
2500 return TDK_Invalid;
2501
2502 // C++ [temp.class.spec.match]p2:
2503 // A partial specialization matches a given actual template
2504 // argument list if the template arguments of the partial
2505 // specialization can be deduced from the actual template argument
2506 // list (14.8.2).
2507
2508 // Unevaluated SFINAE context.
2509 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2510 SFINAETrap Trap(*this);
2511
2512 SmallVector<DeducedTemplateArgument, 4> Deduced;
2513 Deduced.resize(Partial->getTemplateParameters()->size());
2514 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2515 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2516 TemplateArgs, Info, Deduced))
2517 return Result;
2518
2519 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002520 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2521 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002522 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002523 return TDK_InstantiationDepth;
2524
2525 if (Trap.hasErrorOccurred())
2526 return Sema::TDK_SubstitutionFailure;
2527
Richard Smith87d263e2016-12-25 08:05:23 +00002528 return ::FinishTemplateArgumentDeduction(
2529 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002530}
2531
Douglas Gregorfc516c92009-06-26 23:27:24 +00002532/// \brief Determine whether the given type T is a simple-template-id type.
2533static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002534 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002535 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002536 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002537
Douglas Gregorfc516c92009-06-26 23:27:24 +00002538 return false;
2539}
Douglas Gregor9b146582009-07-08 20:55:45 +00002540
2541/// \brief Substitute the explicitly-provided template arguments into the
2542/// given function template according to C++ [temp.arg.explicit].
2543///
2544/// \param FunctionTemplate the function template into which the explicit
2545/// template arguments will be substituted.
2546///
James Dennett634962f2012-06-14 21:40:34 +00002547/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002548/// arguments.
2549///
Mike Stump11289f42009-09-09 15:08:12 +00002550/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002551/// with the converted and checked explicit template arguments.
2552///
Mike Stump11289f42009-09-09 15:08:12 +00002553/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002554/// parameters.
2555///
2556/// \param FunctionType if non-NULL, the result type of the function template
2557/// will also be instantiated and the pointed-to value will be updated with
2558/// the instantiated function type.
2559///
2560/// \param Info if substitution fails for any reason, this object will be
2561/// populated with more information about the failure.
2562///
2563/// \returns TDK_Success if substitution was successful, or some failure
2564/// condition.
2565Sema::TemplateDeductionResult
2566Sema::SubstituteExplicitTemplateArguments(
2567 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002568 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002569 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2570 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002571 QualType *FunctionType,
2572 TemplateDeductionInfo &Info) {
2573 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2574 TemplateParameterList *TemplateParams
2575 = FunctionTemplate->getTemplateParameters();
2576
John McCall6b51f282009-11-23 01:53:49 +00002577 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002578 // No arguments to substitute; just copy over the parameter types and
2579 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002580 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002581 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregor9b146582009-07-08 20:55:45 +00002583 if (FunctionType)
2584 *FunctionType = Function->getType();
2585 return TDK_Success;
2586 }
Mike Stump11289f42009-09-09 15:08:12 +00002587
Eli Friedman77dcc722012-02-08 03:07:05 +00002588 // Unevaluated SFINAE context.
2589 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002590 SFINAETrap Trap(*this);
2591
Douglas Gregor9b146582009-07-08 20:55:45 +00002592 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002593 // Template arguments that are present shall be specified in the
2594 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002595 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002596 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002598
2599 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002600 // explicitly-specified template arguments against this function template,
2601 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002602 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002603 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2604 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002605 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2606 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002607 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002608 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregor9b146582009-07-08 20:55:45 +00002610 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002611 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002612 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002613 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002614 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002615 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002616 if (Index >= TemplateParams->size())
2617 Index = TemplateParams->size() - 1;
2618 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002619 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
Douglas Gregor9b146582009-07-08 20:55:45 +00002622 // Form the template argument list from the explicitly-specified
2623 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002624 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002625 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002626 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002627
John McCall036855a2010-10-12 19:40:14 +00002628 // Template argument deduction and the final substitution should be
2629 // done in the context of the templated declaration. Explicit
2630 // argument substitution, on the other hand, needs to happen in the
2631 // calling context.
2632 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2633
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002635 // note that the template argument pack is partially substituted and record
2636 // the explicit template arguments. They'll be used as part of deduction
2637 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002638 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2639 const TemplateArgument &Arg = Builder[I];
2640 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002641 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002643 Arg.pack_begin(),
2644 Arg.pack_size());
2645 break;
2646 }
2647 }
2648
Richard Smith5e580292012-02-10 09:58:53 +00002649 const FunctionProtoType *Proto
2650 = Function->getType()->getAs<FunctionProtoType>();
2651 assert(Proto && "Function template does not have a prototype?");
2652
Richard Smith70b13042015-01-09 01:19:56 +00002653 // Isolate our substituted parameters from our caller.
2654 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2655
John McCallc8e321d2016-03-01 02:09:25 +00002656 ExtParameterInfoBuilder ExtParamInfos;
2657
Douglas Gregor9b146582009-07-08 20:55:45 +00002658 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002659 // explicitly-specified template arguments. If the function has a trailing
2660 // return type, substitute it after the arguments to ensure we substitute
2661 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002662 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002663 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002664 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002665 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002666 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002667 return TDK_SubstitutionFailure;
2668 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002669
Richard Smith5e580292012-02-10 09:58:53 +00002670 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002671 QualType ResultType;
2672 {
2673 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002674 // If a declaration declares a member function or member function
2675 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002676 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002677 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002678 // declarator.
2679 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002680 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002681 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2682 ThisContext = Method->getParent();
2683 ThisTypeQuals = Method->getTypeQualifiers();
2684 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002685
Douglas Gregor3024f072012-04-16 07:05:22 +00002686 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002687 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002688
2689 ResultType =
2690 SubstType(Proto->getReturnType(),
2691 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2692 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002693 if (ResultType.isNull() || Trap.hasErrorOccurred())
2694 return TDK_SubstitutionFailure;
2695 }
John McCallc8e321d2016-03-01 02:09:25 +00002696
Richard Smith5e580292012-02-10 09:58:53 +00002697 // Instantiate the types of each of the function parameters given the
2698 // explicitly-specified template arguments if we didn't do so earlier.
2699 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002700 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002701 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002702 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002703 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002704 return TDK_SubstitutionFailure;
2705
Douglas Gregor9b146582009-07-08 20:55:45 +00002706 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002707 auto EPI = Proto->getExtProtoInfo();
2708 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002709 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002710 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002711 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002712 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002713 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2714 return TDK_SubstitutionFailure;
2715 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Douglas Gregor9b146582009-07-08 20:55:45 +00002717 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002718 // Trailing template arguments that can be deduced (14.8.2) may be
2719 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002720 // template arguments can be deduced, they may all be omitted; in this
2721 // case, the empty template argument list <> itself may also be omitted.
2722 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002723 // Take all of the explicitly-specified arguments and put them into
2724 // the set of deduced template arguments. Explicitly-specified
2725 // parameter packs, however, will be set to NULL since the deduction
2726 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002727 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002728 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2729 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2730 if (Arg.getKind() == TemplateArgument::Pack)
2731 Deduced.push_back(DeducedTemplateArgument());
2732 else
2733 Deduced.push_back(Arg);
2734 }
Mike Stump11289f42009-09-09 15:08:12 +00002735
Douglas Gregor9b146582009-07-08 20:55:45 +00002736 return TDK_Success;
2737}
2738
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002739/// \brief Check whether the deduced argument type for a call to a function
2740/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002741static bool
2742CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002743 QualType DeducedA) {
2744 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002745
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002746 QualType A = OriginalArg.OriginalArgType;
2747 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002748
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002749 // Check for type equality (top-level cv-qualifiers are ignored).
2750 if (Context.hasSameUnqualifiedType(A, DeducedA))
2751 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002752
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002753 // Strip off references on the argument types; they aren't needed for
2754 // the following checks.
2755 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2756 DeducedA = DeducedARef->getPointeeType();
2757 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2758 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002759
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002760 // C++ [temp.deduct.call]p4:
2761 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002762 // - If the original P is a reference type, the deduced A (i.e., the
2763 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002764 // the transformed A.
2765 if (const ReferenceType *OriginalParamRef
2766 = OriginalParamType->getAs<ReferenceType>()) {
2767 // We don't want to keep the reference around any more.
2768 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002769
Richard Smith1be59c52016-10-22 01:32:19 +00002770 // FIXME: Resolve core issue (no number yet): if the original P is a
2771 // reference type and the transformed A is function type "noexcept F",
2772 // the deduced A can be F.
2773 QualType Tmp;
2774 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2775 return false;
2776
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002777 Qualifiers AQuals = A.getQualifiers();
2778 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002779
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002780 // Under Objective-C++ ARC, the deduced type may have implicitly
2781 // been given strong or (when dealing with a const reference)
2782 // unsafe_unretained lifetime. If so, update the original
2783 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002784 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002785 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2786 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2787 (DeducedAQuals.hasConst() &&
2788 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2789 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002790 }
2791
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002792 if (AQuals == DeducedAQuals) {
2793 // Qualifiers match; there's nothing to do.
2794 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002795 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002796 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002797 // Qualifiers are compatible, so have the argument type adopt the
2798 // deduced argument type's qualifiers as if we had performed the
2799 // qualification conversion.
2800 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2801 }
2802 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002803
2804 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002805 // type that can be converted to the deduced A via a function pointer
2806 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002807 //
Richard Smith1be59c52016-10-22 01:32:19 +00002808 // Also allow conversions which merely strip __attribute__((noreturn)) from
2809 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002811 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002812 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002813 (S.IsQualificationConversion(A, DeducedA, false,
2814 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002815 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002816 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002817
Simon Pilgrim728134c2016-08-12 11:43:57 +00002818 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002819 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002820 // [...] Likewise, if P is a pointer to a class of the form
2821 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002822 // derived class pointed to by the deduced A.
2823 if (const PointerType *OriginalParamPtr
2824 = OriginalParamType->getAs<PointerType>()) {
2825 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2826 if (const PointerType *APtr = A->getAs<PointerType>()) {
2827 if (A->getPointeeType()->isRecordType()) {
2828 OriginalParamType = OriginalParamPtr->getPointeeType();
2829 DeducedA = DeducedAPtr->getPointeeType();
2830 A = APtr->getPointeeType();
2831 }
2832 }
2833 }
2834 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002835
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002836 if (Context.hasSameUnqualifiedType(A, DeducedA))
2837 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002838
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002839 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002840 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002841 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002842
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002843 return true;
2844}
2845
Mike Stump11289f42009-09-09 15:08:12 +00002846/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002847/// checking the deduced template arguments for completeness and forming
2848/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002849///
2850/// \param OriginalCallArgs If non-NULL, the original call arguments against
2851/// which the deduced argument types should be compared.
Richard Smithefcfe862017-01-02 02:42:17 +00002852Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2853 FunctionTemplateDecl *FunctionTemplate,
2854 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2855 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
2856 TemplateDeductionInfo &Info,
2857 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2858 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002859 // Unevaluated SFINAE context.
2860 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002861 SFINAETrap Trap(*this);
2862
Douglas Gregor9b146582009-07-08 20:55:45 +00002863 // Enter a new template instantiation context while we instantiate the
2864 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002865 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002866 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2867 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002868 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2869 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002870 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002871 return TDK_InstantiationDepth;
2872
John McCalle23b8712010-04-29 01:18:58 +00002873 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002874
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002875 // C++ [temp.deduct.type]p2:
2876 // [...] or if any template argument remains neither deduced nor
2877 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002878 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002879 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002880 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002881 CurrentInstantiationScope, NumExplicitlySpecified,
2882 PartialOverloading))
2883 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002884
Richard Smithefcfe862017-01-02 02:42:17 +00002885 // C++ [temp.deduct.call]p10: [DR1391]
2886 // If deduction succeeds for all parameters that contain
2887 // template-parameters that participate in template argument deduction,
2888 // and all template arguments are explicitly specified, deduced, or
2889 // obtained from default template arguments, remaining parameters are then
2890 // compared with the corresponding arguments. For each remaining parameter
2891 // P with a type that was non-dependent before substitution of any
2892 // explicitly-specified template arguments, if the corresponding argument
2893 // A cannot be implicitly converted to P, deduction fails.
2894 if (CheckNonDependent())
2895 return TDK_NonDependentConversionFailure;
2896
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002897 // Form the template argument list from the deduced template arguments.
2898 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002899 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002900 Info.reset(DeducedArgumentList);
2901
Mike Stump11289f42009-09-09 15:08:12 +00002902 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002903 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002904 DeclContext *Owner = FunctionTemplate->getDeclContext();
2905 if (FunctionTemplate->getFriendObjectKind())
2906 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002907 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002908 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002909 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002910 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002911 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002914 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915
Mike Stump11289f42009-09-09 15:08:12 +00002916 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002917 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002918 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2919 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002920 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002921
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002922 // There may have been an error that did not prevent us from constructing a
2923 // declaration. Mark the declaration invalid and return with a substitution
2924 // failure.
2925 if (Trap.hasErrorOccurred()) {
2926 Specialization->setInvalidDecl(true);
2927 return TDK_SubstitutionFailure;
2928 }
2929
Douglas Gregore65aacb2011-06-16 16:50:48 +00002930 if (OriginalCallArgs) {
2931 // C++ [temp.deduct.call]p4:
2932 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002933 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002934 // is transformed as described above). [...]
2935 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2936 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002937 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002938
Douglas Gregore65aacb2011-06-16 16:50:48 +00002939 if (ParamIdx >= Specialization->getNumParams())
2940 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002941
Douglas Gregore65aacb2011-06-16 16:50:48 +00002942 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002943 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2944 Info.FirstArg = TemplateArgument(DeducedA);
2945 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2946 Info.CallArgIndex = OriginalArg.ArgIdx;
2947 return TDK_DeducedMismatch;
2948 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002949 }
2950 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002951
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002952 // If we suppressed any diagnostics while performing template argument
2953 // deduction, and if we haven't already instantiated this declaration,
2954 // keep track of these diagnostics. They'll be emitted if this specialization
2955 // is actually used.
2956 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002957 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002958 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2959 if (Pos == SuppressedDiagnostics.end())
2960 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2961 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002963
Mike Stump11289f42009-09-09 15:08:12 +00002964 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002965}
2966
John McCall8d08b9b2010-08-27 09:08:28 +00002967/// Gets the type of a function for template-argument-deducton
2968/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002969static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002970 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002972 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002973 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002974 return QualType();
2975
John McCallc1f69982010-02-02 02:21:27 +00002976 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002977 if (Method->isInstance()) {
2978 // An instance method that's referenced in a form that doesn't
2979 // look like a member pointer is just invalid.
2980 if (!R.HasFormOfMemberPointer) return QualType();
2981
Richard Smith2a7d4812013-05-04 07:00:32 +00002982 return S.Context.getMemberPointerType(Fn->getType(),
2983 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002984 }
2985
2986 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002987 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002988}
2989
2990/// Apply the deduction rules for overload sets.
2991///
2992/// \return the null type if this argument should be treated as an
2993/// undeduced context
2994static QualType
2995ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002996 Expr *Arg, QualType ParamType,
2997 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998
John McCall8d08b9b2010-08-27 09:08:28 +00002999 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003000
John McCall8d08b9b2010-08-27 09:08:28 +00003001 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003002
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003003 // C++0x [temp.deduct.call]p4
3004 unsigned TDF = 0;
3005 if (ParamWasReference)
3006 TDF |= TDF_ParamWithReferenceType;
3007 if (R.IsAddressOfOperand)
3008 TDF |= TDF_IgnoreQualifiers;
3009
John McCallc1f69982010-02-02 02:21:27 +00003010 // C++0x [temp.deduct.call]p6:
3011 // When P is a function type, pointer to function type, or pointer
3012 // to member function type:
3013
3014 if (!ParamType->isFunctionType() &&
3015 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003016 !ParamType->isMemberFunctionPointerType()) {
3017 if (Ovl->hasExplicitTemplateArgs()) {
3018 // But we can still look for an explicit specialization.
3019 if (FunctionDecl *ExplicitSpec
3020 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003021 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003022 }
John McCallc1f69982010-02-02 02:21:27 +00003023
George Burgess IVcc2f3552016-03-19 21:51:45 +00003024 DeclAccessPair DAP;
3025 if (FunctionDecl *Viable =
3026 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3027 return GetTypeOfFunction(S, R, Viable);
3028
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003029 return QualType();
3030 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003031
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003032 // Gather the explicit template arguments, if any.
3033 TemplateArgumentListInfo ExplicitTemplateArgs;
3034 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003035 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003036 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003037 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3038 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003039 NamedDecl *D = (*I)->getUnderlyingDecl();
3040
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003041 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3042 // - If the argument is an overload set containing one or more
3043 // function templates, the parameter is treated as a
3044 // non-deduced context.
3045 if (!Ovl->hasExplicitTemplateArgs())
3046 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003047
3048 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003049 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003050 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003051 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3052 Specialization, Info))
3053 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003054
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003055 D = Specialization;
3056 }
John McCallc1f69982010-02-02 02:21:27 +00003057
3058 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003059 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003060 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003061
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003062 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003064 ArgType->isFunctionType())
3065 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066
John McCallc1f69982010-02-02 02:21:27 +00003067 // - If the argument is an overload set (not containing function
3068 // templates), trial argument deduction is attempted using each
3069 // of the members of the set. If deduction succeeds for only one
3070 // of the overload set members, that member is used as the
3071 // argument value for the deduction. If deduction succeeds for
3072 // more than one member of the overload set the parameter is
3073 // treated as a non-deduced context.
3074
3075 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3076 // Type deduction is done independently for each P/A pair, and
3077 // the deduced template argument values are then combined.
3078 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003079 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003080 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003081 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003082 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003083 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3084 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003085 if (Result) continue;
3086 if (!Match.isNull()) return QualType();
3087 Match = ArgType;
3088 }
3089
3090 return Match;
3091}
3092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003093/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003094/// described in C++ [temp.deduct.call].
3095///
3096/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003097/// argument deduction based on this P/A pair because the argument is an
3098/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003099static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3100 TemplateParameterList *TemplateParams,
3101 QualType &ParamType,
3102 QualType &ArgType,
3103 Expr *Arg,
3104 unsigned &TDF) {
3105 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003106 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003107 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003108 if (ParamType.hasQualifiers())
3109 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003110
3111 // [...] If P is a reference type, the type referred to by P is
3112 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003113 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003114 if (ParamRefType)
3115 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003116
Nathan Sidwell96090022015-01-16 15:20:14 +00003117 // Overload sets usually make this parameter an undeduced context,
3118 // but there are sometimes special circumstances. Typically
3119 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003120 if (ArgType == S.Context.OverloadTy) {
3121 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3122 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003123 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003124 if (ArgType.isNull())
3125 return true;
3126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127
Douglas Gregor7825bf32011-01-06 22:09:01 +00003128 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003129 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003130 if (ArgType->isIncompleteArrayType()) {
3131 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003132 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003133 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003134
Douglas Gregor7825bf32011-01-06 22:09:01 +00003135 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003136 // If P is an rvalue reference to a cv-unqualified template
3137 // parameter and the argument is an lvalue, the type "lvalue
3138 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003139 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003140 !ParamType.getQualifiers() &&
3141 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003142 Arg->isLValue())
3143 ArgType = S.Context.getLValueReferenceType(ArgType);
3144 } else {
3145 // C++ [temp.deduct.call]p2:
3146 // If P is not a reference type:
3147 // - If A is an array type, the pointer type produced by the
3148 // array-to-pointer standard conversion (4.2) is used in place of
3149 // A for type deduction; otherwise,
3150 if (ArgType->isArrayType())
3151 ArgType = S.Context.getArrayDecayedType(ArgType);
3152 // - If A is a function type, the pointer type produced by the
3153 // function-to-pointer standard conversion (4.3) is used in place
3154 // of A for type deduction; otherwise,
3155 else if (ArgType->isFunctionType())
3156 ArgType = S.Context.getPointerType(ArgType);
3157 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003158 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003160 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003161 }
3162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
Douglas Gregor7825bf32011-01-06 22:09:01 +00003164 // C++0x [temp.deduct.call]p4:
3165 // In general, the deduction process attempts to find template argument
3166 // values that will make the deduced A identical to A (after the type A
3167 // is transformed as described above). [...]
3168 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003169
Douglas Gregor7825bf32011-01-06 22:09:01 +00003170 // - If the original P is a reference type, the deduced A (i.e., the
3171 // type referred to by the reference) can be more cv-qualified than
3172 // the transformed A.
3173 if (ParamRefType)
3174 TDF |= TDF_ParamWithReferenceType;
3175 // - The transformed A can be another pointer or pointer to member
3176 // type that can be converted to the deduced A via a qualification
3177 // conversion (4.4).
3178 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3179 ArgType->isObjCObjectPointerType())
3180 TDF |= TDF_IgnoreQualifiers;
3181 // - If P is a class and P has the form simple-template-id, then the
3182 // transformed A can be a derived class of the deduced A. Likewise,
3183 // if P is a pointer to a class of the form simple-template-id, the
3184 // transformed A can be a pointer to a derived class pointed to by
3185 // the deduced A.
3186 if (isSimpleTemplateIdType(ParamType) ||
3187 (isa<PointerType>(ParamType) &&
3188 isSimpleTemplateIdType(
3189 ParamType->getAs<PointerType>()->getPointeeType())))
3190 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
Douglas Gregor7825bf32011-01-06 22:09:01 +00003192 return false;
3193}
3194
Nico Weberc153d242014-07-28 00:02:09 +00003195static bool
3196hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3197 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003198
Hubert Tong3280b332015-06-25 00:25:49 +00003199static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3200 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3201 Expr *Arg, TemplateDeductionInfo &Info,
3202 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3203
3204/// \brief Attempt template argument deduction from an initializer list
3205/// deemed to be an argument in a function call.
3206static bool
3207DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3208 QualType AdjustedParamType, InitListExpr *ILE,
3209 TemplateDeductionInfo &Info,
3210 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3211 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003212
3213 // [temp.deduct.call] p1 (post CWG-1591)
3214 // If removing references and cv-qualifiers from P gives
3215 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3216 // non-empty initializer list (8.5.4), then deduction is performed instead for
3217 // each element of the initializer list, taking P0 as a function template
3218 // parameter type and the initializer element as its argument, and in the
3219 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3220 // length of the initializer list. Otherwise, an initializer list argument
3221 // causes the parameter to be considered a non-deduced context
3222
3223 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3224
3225 const bool IsDependentSizedArray =
3226 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3227
Faisal Validd76cc12015-12-10 12:29:11 +00003228 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003229
3230 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3231 S.isStdInitializerList(AdjustedParamType, &ElTy);
3232
3233 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003234 return false;
3235
3236 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003237 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3238 // deduce against the 'T' in T[N].
3239 if (ElTy.isNull()) {
3240 assert(!IsSTDList);
3241 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003242 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003243 // Deduction only needs to be done for dependent types.
3244 if (ElTy->isDependentType()) {
3245 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003246 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3247 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003248 return true;
3249 }
3250 }
3251 if (IsDependentSizedArray) {
3252 const DependentSizedArrayType *ArrTy =
3253 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3254 // Determine the array bound is something we can deduce.
3255 if (NonTypeTemplateParmDecl *NTTP =
Richard Smith87d263e2016-12-25 08:05:23 +00003256 getDeducedParameterFromExpr(Info, ArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003257 // We can perform template argument deduction for the given non-type
3258 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003259 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3260 ILE->getNumInits());
Faisal Valif6dfdb32015-12-10 05:36:39 +00003261 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003262 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003263 /*ArrayBound=*/true, Info, Deduced);
3264 }
3265 }
Hubert Tong3280b332015-06-25 00:25:49 +00003266 return true;
3267}
3268
Sebastian Redl19181662012-03-15 21:40:51 +00003269/// \brief Perform template argument deduction by matching a parameter type
3270/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003271/// an initializer list that was originally matched against a parameter
3272/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003273static Sema::TemplateDeductionResult
3274DeduceTemplateArgumentByListElement(Sema &S,
3275 TemplateParameterList *TemplateParams,
3276 QualType ParamType, Expr *Arg,
3277 TemplateDeductionInfo &Info,
3278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3279 unsigned TDF) {
3280 // Handle the case where an init list contains another init list as the
3281 // element.
3282 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003283 Sema::TemplateDeductionResult Result;
3284 if (!DeduceFromInitializerList(S, TemplateParams,
3285 ParamType.getNonReferenceType(), ILE, Info,
3286 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003287 return Sema::TDK_Success; // Just ignore this expression.
3288
Hubert Tong3280b332015-06-25 00:25:49 +00003289 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003290 }
3291
3292 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003293 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003294 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003295 ArgType, Arg, TDF)) {
3296 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003297 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003298 }
Sebastian Redl19181662012-03-15 21:40:51 +00003299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003300 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003301}
3302
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303/// \brief Perform template argument deduction from a function call
3304/// (C++ [temp.deduct.call]).
3305///
3306/// \param FunctionTemplate the function template for which we are performing
3307/// template argument deduction.
3308///
James Dennett18348b62012-06-22 08:52:37 +00003309/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003310/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003311///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312/// \param Args the function call arguments
3313///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003315/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003316/// template argument deduction.
3317///
3318/// \param Info the argument will be updated to provide additional information
3319/// about template argument deduction.
3320///
Richard Smithefcfe862017-01-02 02:42:17 +00003321/// \param CheckNonDependent A callback to invoke to check conversions for
3322/// non-dependent parameters, between deduction and substitution, per DR1391.
3323/// If this returns true, substitution will be skipped and we return
3324/// TDK_NonDependentConversionFailure.
3325///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003326/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003327Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3328 FunctionTemplateDecl *FunctionTemplate,
3329 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003330 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smithefcfe862017-01-02 02:42:17 +00003331 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003332 if (FunctionTemplate->isInvalidDecl())
3333 return TDK_Invalid;
3334
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003335 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003336 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003337
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 // C++ [temp.deduct.call]p1:
3339 // Template argument deduction is done by comparing each function template
3340 // parameter type (call it P) with the type of the corresponding argument
3341 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003342 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003343 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003344 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003345 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003346 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003347 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003348 if (Proto->isTemplateVariadic())
3349 /* Do nothing */;
3350 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003351 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003353 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 }
Mike Stump11289f42009-09-09 15:08:12 +00003355
Douglas Gregor89026b52009-06-30 23:57:56 +00003356 // The types of the parameters from which we will perform template argument
3357 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003358 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003359 TemplateParameterList *TemplateParams
3360 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003361 SmallVector<DeducedTemplateArgument, 4> Deduced;
3362 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003363 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003364 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003365 TemplateDeductionResult Result =
3366 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003367 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003368 Deduced,
3369 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003370 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003371 Info);
3372 if (Result)
3373 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003374
3375 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003376 } else {
3377 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003378 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003379 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3380 }
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregor89026b52009-06-30 23:57:56 +00003382 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003383 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003384 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003385 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003386 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3387 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003388 QualType OrigParamType = ParamTypes[ParamIdx];
3389 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003390
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003392 = dyn_cast<PackExpansionType>(ParamType);
3393 if (!ParamExpansion) {
3394 // Simple case: matching a function parameter to a function argument.
3395 if (ArgIdx >= CheckArgs)
3396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397
Douglas Gregor7825bf32011-01-06 22:09:01 +00003398 Expr *Arg = Args[ArgIdx++];
3399 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003400
Douglas Gregor7825bf32011-01-06 22:09:01 +00003401 unsigned TDF = 0;
3402 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3403 ParamType, ArgType, Arg,
3404 TDF))
3405 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406
Douglas Gregor0c83c812011-10-09 22:06:46 +00003407 // If we have nothing to deduce, we're done.
3408 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3409 continue;
3410
Sebastian Redl43144e72012-01-17 22:49:58 +00003411 // If the argument is an initializer list ...
3412 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003413 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003414 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003415 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3416 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003417 continue;
3418
Hubert Tong3280b332015-06-25 00:25:49 +00003419 if (Result)
3420 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003421 // Don't track the argument type, since an initializer list has none.
3422 continue;
3423 }
3424
Douglas Gregore65aacb2011-06-16 16:50:48 +00003425 // Keep track of the argument type and corresponding parameter index,
3426 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003427 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003428 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003429
Douglas Gregor7825bf32011-01-06 22:09:01 +00003430 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003431 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3432 ParamType, ArgType,
3433 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregor7825bf32011-01-06 22:09:01 +00003436 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregor7825bf32011-01-06 22:09:01 +00003439 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 // For a function parameter pack that occurs at the end of the
3441 // parameter-declaration-list, the type A of each remaining argument of
3442 // the call is compared with the type P of the declarator-id of the
3443 // function parameter pack. Each comparison deduces template arguments
3444 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003445 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003447 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003448 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003449 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregor7825bf32011-01-06 22:09:01 +00003451 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003452 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3453 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Douglas Gregor7825bf32011-01-06 22:09:01 +00003455 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003456 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003457 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
Douglas Gregore65aacb2011-06-16 16:50:48 +00003459 QualType OrigParamType = ParamPattern;
3460 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003461 Expr *Arg = Args[ArgIdx];
3462 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003463
Douglas Gregor7825bf32011-01-06 22:09:01 +00003464 unsigned TDF = 0;
3465 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3466 ParamType, ArgType, Arg,
3467 TDF)) {
3468 // We can't actually perform any deduction for this argument, so stop
3469 // deduction at this point.
3470 ++ArgIdx;
3471 break;
3472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Sebastian Redl43144e72012-01-17 22:49:58 +00003474 // As above, initializer lists need special handling.
3475 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003476 TemplateDeductionResult Result;
3477 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3478 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003479 ++ArgIdx;
3480 break;
3481 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003482
Hubert Tong3280b332015-06-25 00:25:49 +00003483 if (Result)
3484 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003485 } else {
3486
3487 // Keep track of the argument type and corresponding argument index,
3488 // so we can check for compatibility between the deduced A and A.
3489 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003490 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003491 ArgType));
3492
3493 if (TemplateDeductionResult Result
3494 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3495 ParamType, ArgType, Info,
3496 Deduced, TDF))
3497 return Result;
3498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Richard Smith0a80d572014-05-29 01:12:14 +00003500 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor7825bf32011-01-06 22:09:01 +00003503 // Build argument packs for each of the parameter packs expanded by this
3504 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003505 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003507
Douglas Gregor7825bf32011-01-06 22:09:01 +00003508 // After we've matching against a parameter pack, we're done.
3509 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003510 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003511
Mike Stump11289f42009-09-09 15:08:12 +00003512 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003513 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003514 Info, &OriginalCallArgs,
Richard Smithefcfe862017-01-02 02:42:17 +00003515 PartialOverloading, CheckNonDependent);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003516}
3517
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003518QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003519 QualType FunctionType,
3520 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003521 if (ArgFunctionType.isNull())
3522 return ArgFunctionType;
3523
3524 const FunctionProtoType *FunctionTypeP =
3525 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003526 const FunctionProtoType *ArgFunctionTypeP =
3527 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003528
3529 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3530 bool Rebuild = false;
3531
3532 CallingConv CC = FunctionTypeP->getCallConv();
3533 if (EPI.ExtInfo.getCC() != CC) {
3534 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3535 Rebuild = true;
3536 }
3537
3538 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3539 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3540 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3541 Rebuild = true;
3542 }
3543
3544 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3545 ArgFunctionTypeP->hasExceptionSpec())) {
3546 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3547 Rebuild = true;
3548 }
3549
3550 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003551 return ArgFunctionType;
3552
Richard Smithbaa47832016-12-01 02:11:49 +00003553 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3554 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003555}
3556
Douglas Gregor9b146582009-07-08 20:55:45 +00003557/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003558/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3559/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003560///
3561/// \param FunctionTemplate the function template for which we are performing
3562/// template argument deduction.
3563///
James Dennett18348b62012-06-22 08:52:37 +00003564/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003565/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003566///
3567/// \param ArgFunctionType the function type that will be used as the
3568/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003569/// function template's function type. This type may be NULL, if there is no
3570/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003571///
3572/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003573/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003574/// template argument deduction.
3575///
3576/// \param Info the argument will be updated to provide additional information
3577/// about template argument deduction.
3578///
Richard Smithbaa47832016-12-01 02:11:49 +00003579/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3580/// the address of a function template per [temp.deduct.funcaddr] and
3581/// [over.over]. If \c false, we are looking up a function template
3582/// specialization based on its signature, per [temp.deduct.decl].
3583///
Douglas Gregor9b146582009-07-08 20:55:45 +00003584/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003585Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3586 FunctionTemplateDecl *FunctionTemplate,
3587 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3588 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3589 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003590 if (FunctionTemplate->isInvalidDecl())
3591 return TDK_Invalid;
3592
Douglas Gregor9b146582009-07-08 20:55:45 +00003593 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3594 TemplateParameterList *TemplateParams
3595 = FunctionTemplate->getTemplateParameters();
3596 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003597
3598 // When taking the address of a function, we require convertibility of
3599 // the resulting function type. Otherwise, we allow arbitrary mismatches
3600 // of calling convention, noreturn, and noexcept.
3601 if (!IsAddressOfFunction)
3602 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3603 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregor9b146582009-07-08 20:55:45 +00003605 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003606 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003607 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003608 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003609 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003610 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003611 if (TemplateDeductionResult Result
3612 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003613 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003614 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003615 &FunctionType, Info))
3616 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003617
3618 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003619 }
3620
Eli Friedman77dcc722012-02-08 03:07:05 +00003621 // Unevaluated SFINAE context.
3622 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003623 SFINAETrap Trap(*this);
3624
John McCallc1f69982010-02-02 02:21:27 +00003625 Deduced.resize(TemplateParams->size());
3626
Richard Smith2a7d4812013-05-04 07:00:32 +00003627 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003628 // type so that we treat it as a non-deduced context in what follows. If we
3629 // are looking up by signature, the signature type should also have a deduced
3630 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003631 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003632 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003633 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003634 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003635 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003636 }
3637
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003638 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003639 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003640 if (IsAddressOfFunction)
3641 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003642 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003643 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003644 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003645 FunctionType, ArgFunctionType,
3646 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003647 return Result;
3648 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003649
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003651 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3652 NumExplicitlySpecified,
3653 Specialization, Info))
3654 return Result;
3655
Richard Smith2a7d4812013-05-04 07:00:32 +00003656 // If the function has a deduced return type, deduce it now, so we can check
3657 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003658 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003659 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003660 DeduceReturnType(Specialization, Info.getLocation(), false))
3661 return TDK_MiscellaneousDeductionFailure;
3662
Richard Smith9095e5b2016-11-01 01:31:23 +00003663 // If the function has a dependent exception specification, resolve it now,
3664 // so we can check that the exception specification matches.
3665 auto *SpecializationFPT =
3666 Specialization->getType()->castAs<FunctionProtoType>();
3667 if (getLangOpts().CPlusPlus1z &&
3668 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3669 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3670 return TDK_MiscellaneousDeductionFailure;
3671
Richard Smithbaa47832016-12-01 02:11:49 +00003672 // Adjust the exception specification of the argument again to match the
3673 // substituted and resolved type we just formed. (Calling convention and
3674 // noreturn can't be dependent, so we don't actually need this for them
3675 // right now.)
3676 QualType SpecializationType = Specialization->getType();
3677 if (!IsAddressOfFunction)
3678 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3679 /*AdjustExceptionSpec*/true);
3680
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003681 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003682 // specialization with respect to arguments of compatible pointer to function
3683 // types, template argument deduction fails.
3684 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003685 if (IsAddressOfFunction &&
3686 !isSameOrCompatibleFunctionType(
3687 Context.getCanonicalType(SpecializationType),
3688 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003689 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003690
3691 if (!IsAddressOfFunction &&
3692 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003693 return TDK_MiscellaneousDeductionFailure;
3694 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003695
3696 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003697}
3698
Simon Pilgrim728134c2016-08-12 11:43:57 +00003699/// \brief Given a function declaration (e.g. a generic lambda conversion
3700/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003701/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3702/// to replace 'auto' with and not the actual result type you want
3703/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003704static inline void
3705SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003706 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003708 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003709 assert(AutoResultType->getContainedAutoType());
3710 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003711 TypeToReplaceAutoWith);
3712 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3713}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714
Simon Pilgrim728134c2016-08-12 11:43:57 +00003715/// \brief Given a specialized conversion operator of a generic lambda
3716/// create the corresponding specializations of the call operator and
3717/// the static-invoker. If the return type of the call operator is auto,
3718/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003719/// return type of the destination function ptr.
3720
Simon Pilgrim728134c2016-08-12 11:43:57 +00003721static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003722SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3723 CXXConversionDecl *ConversionSpecialized,
3724 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3725 QualType ReturnTypeOfDestFunctionPtr,
3726 TemplateDeductionInfo &TDInfo,
3727 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003728
Faisal Vali2b3a3012013-10-24 23:40:02 +00003729 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003730 assert(LambdaClass && LambdaClass->isGenericLambda());
3731
Faisal Vali2b3a3012013-10-24 23:40:02 +00003732 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003733 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003734 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003736
3737 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003738 CallOpGeneric->getDescribedFunctionTemplate();
3739
Craig Topperc3ec1492014-05-26 06:22:03 +00003740 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003741 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003742 // generic lambda's call operator.
3743 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003744 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3745 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003746 0, CallOpSpecialized, TDInfo))
3747 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003748
Faisal Vali2b3a3012013-10-24 23:40:02 +00003749 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003750 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3751 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003752 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003753 CallOpSpecialized->getPointOfInstantiation(),
3754 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003755
Faisal Vali2b3a3012013-10-24 23:40:02 +00003756 // Check to see if the return type of the destination ptr-to-function
3757 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003758 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003759 ReturnTypeOfDestFunctionPtr))
3760 return Sema::TDK_NonDeducedMismatch;
3761 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003762 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003763 // specialized our corresponding call operator, we are ready to
3764 // specialize the static invoker with the deduced arguments of our
3765 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003766 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003767 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3768 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3769
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003770#ifndef NDEBUG
3771 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3772#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003773 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003774 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003775 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 "If the call operator succeeded so should the invoker!");
3777 // Set the result type to match the corresponding call operator
3778 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003779 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3780 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003781 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003782 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003783 // to substitute into the 'auto' of the invoker and conversion
3784 // function.
3785 // For e.g.
3786 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3787 // We don't want to subst 'int*' into 'auto' to get int**.
3788
Alp Toker314cc812014-01-25 16:55:45 +00003789 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3790 ->getContainedAutoType()
3791 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003792 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3793 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003794 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003795 TypeToReplaceAutoWith, S);
3796 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003797
Faisal Vali2b3a3012013-10-24 23:40:02 +00003798 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003799 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003800 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003801 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003802 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3803 getType().getTypePtr()->castAs<FunctionProtoType>();
3804 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3805 EPI.TypeQuals = 0;
3806 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003807 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003808 return Sema::TDK_Success;
3809}
Douglas Gregor05155d82009-08-21 23:19:43 +00003810/// \brief Deduce template arguments for a templated conversion
3811/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3812/// conversion function template specialization.
3813Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003814Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003815 QualType ToType,
3816 CXXConversionDecl *&Specialization,
3817 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003818 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003819 return TDK_Invalid;
3820
Faisal Vali2b3a3012013-10-24 23:40:02 +00003821 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003822 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3823
Faisal Vali2b3a3012013-10-24 23:40:02 +00003824 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003825
3826 // Canonicalize the types for deduction.
3827 QualType P = Context.getCanonicalType(FromType);
3828 QualType A = Context.getCanonicalType(ToType);
3829
Douglas Gregord99609a2011-03-06 09:03:20 +00003830 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003831 // If P is a reference type, the type referred to by P is used for
3832 // type deduction.
3833 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3834 P = PRef->getPointeeType();
3835
Douglas Gregord99609a2011-03-06 09:03:20 +00003836 // C++0x [temp.deduct.conv]p4:
3837 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003838 // for type deduction.
3839 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003840 A = ARef->getPointeeType().getUnqualifiedType();
3841 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 //
Mike Stump11289f42009-09-09 15:08:12 +00003843 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 else {
3845 assert(!A->isReferenceType() && "Reference types were handled above");
3846
3847 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003848 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003849 // of P for type deduction; otherwise,
3850 if (P->isArrayType())
3851 P = Context.getArrayDecayedType(P);
3852 // - If P is a function type, the pointer type produced by the
3853 // function-to-pointer standard conversion (4.3) is used in
3854 // place of P for type deduction; otherwise,
3855 else if (P->isFunctionType())
3856 P = Context.getPointerType(P);
3857 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003858 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003859 else
3860 P = P.getUnqualifiedType();
3861
Douglas Gregord99609a2011-03-06 09:03:20 +00003862 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003863 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003864 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003865 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003866 A = A.getUnqualifiedType();
3867 }
3868
Eli Friedman77dcc722012-02-08 03:07:05 +00003869 // Unevaluated SFINAE context.
3870 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003871 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003872
3873 // C++ [temp.deduct.conv]p1:
3874 // Template argument deduction is done by comparing the return
3875 // type of the template conversion function (call it P) with the
3876 // type that is required as the result of the conversion (call it
3877 // A) as described in 14.8.2.4.
3878 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003879 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003880 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003881 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003882
3883 // C++0x [temp.deduct.conv]p4:
3884 // In general, the deduction process attempts to find template
3885 // argument values that will make the deduced A identical to
3886 // A. However, there are two cases that allow a difference:
3887 unsigned TDF = 0;
3888 // - If the original A is a reference type, A can be more
3889 // cv-qualified than the deduced A (i.e., the type referred to
3890 // by the reference)
3891 if (ToType->isReferenceType())
3892 TDF |= TDF_ParamWithReferenceType;
3893 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003894 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003895 // conversion.
3896 //
3897 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3898 // both P and A are pointers or member pointers. In this case, we
3899 // just ignore cv-qualifiers completely).
3900 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003901 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003902 TDF |= TDF_IgnoreQualifiers;
3903 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003904 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3905 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003906 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003907
3908 // Create an Instantiation Scope for finalizing the operator.
3909 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003910 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003911 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003912 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003913 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003914 ConversionSpecialized, Info);
3915 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3916
3917 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003918 // to a ptr-to-function, use the deduced arguments from the conversion
3919 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003920 // e.g., int (*fp)(int) = [](auto a) { return a; };
3921 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003922
Faisal Vali2b3a3012013-10-24 23:40:02 +00003923 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003924 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003925 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003926 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003927 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003928 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003929 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003930 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3931
Simon Pilgrim728134c2016-08-12 11:43:57 +00003932 // Create the corresponding specializations of the call operator and
3933 // the static-invoker; and if the return type is auto,
3934 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003935 // DestFunctionPtrReturnType.
3936 // For instance:
3937 // auto L = [](auto a) { return f(a); };
3938 // int (*fp)(int) = L;
3939 // char (*fp2)(int) = L; <-- Not OK.
3940
3941 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003942 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003943 Info, *this);
3944 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003945 return Result;
3946}
3947
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003948/// \brief Deduce template arguments for a function template when there is
3949/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3950///
3951/// \param FunctionTemplate the function template for which we are performing
3952/// template argument deduction.
3953///
James Dennett18348b62012-06-22 08:52:37 +00003954/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003955/// arguments.
3956///
3957/// \param Specialization if template argument deduction was successful,
3958/// this will be set to the function template specialization produced by
3959/// template argument deduction.
3960///
3961/// \param Info the argument will be updated to provide additional information
3962/// about template argument deduction.
3963///
Richard Smithbaa47832016-12-01 02:11:49 +00003964/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3965/// the address of a function template in a context where we do not have a
3966/// target type, per [over.over]. If \c false, we are looking up a function
3967/// template specialization based on its signature, which only happens when
3968/// deducing a function parameter type from an argument that is a template-id
3969/// naming a function template specialization.
3970///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003971/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003972Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3973 FunctionTemplateDecl *FunctionTemplate,
3974 TemplateArgumentListInfo *ExplicitTemplateArgs,
3975 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3976 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003977 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003978 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003979 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003980}
3981
Richard Smith30482bc2011-02-20 03:19:35 +00003982namespace {
3983 /// Substitute the 'auto' type specifier within a type for a given replacement
3984 /// type.
3985 class SubstituteAutoTransform :
3986 public TreeTransform<SubstituteAutoTransform> {
3987 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003988 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003989 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003990 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3991 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003992 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003993 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003994
Richard Smith30482bc2011-02-20 03:19:35 +00003995 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3996 // If we're building the type pattern to deduce against, don't wrap the
3997 // substituted type in an AutoType. Certain template deduction rules
3998 // apply only when a template type parameter appears directly (and not if
3999 // the parameter is found through desugaring). For instance:
4000 // auto &&lref = lvalue;
4001 // must transform into "rvalue reference to T" not "rvalue reference to
4002 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00004003 if (!UseAutoSugar) {
4004 assert(isa<TemplateTypeParmType>(Replacement) &&
4005 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00004006 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00004007 TemplateTypeParmTypeLoc NewTL =
4008 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00004009 NewTL.setNameLoc(TL.getNameLoc());
4010 return Result;
4011 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00004012 QualType Result = SemaRef.Context.getAutoType(
4013 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00004014 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4015 NewTL.setNameLoc(TL.getNameLoc());
4016 return Result;
4017 }
4018 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004019
4020 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4021 // Lambdas never need to be transformed.
4022 return E;
4023 }
Richard Smith061f1e22013-04-30 21:23:01 +00004024
Richard Smith2a7d4812013-05-04 07:00:32 +00004025 QualType Apply(TypeLoc TL) {
4026 // Create some scratch storage for the transformed type locations.
4027 // FIXME: We're just going to throw this information away. Don't build it.
4028 TypeLocBuilder TLB;
4029 TLB.reserve(TL.getFullDataSize());
4030 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004031 }
Richard Smith30482bc2011-02-20 03:19:35 +00004032 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004033}
Richard Smith30482bc2011-02-20 03:19:35 +00004034
Richard Smith2a7d4812013-05-04 07:00:32 +00004035Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004036Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4037 Optional<unsigned> DependentDeductionDepth) {
4038 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4039 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004040}
4041
Richard Smith061f1e22013-04-30 21:23:01 +00004042/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004043///
Richard Smith87d263e2016-12-25 08:05:23 +00004044/// Note that this is done even if the initializer is dependent. (This is
4045/// necessary to support partial ordering of templates using 'auto'.)
4046/// A dependent type will be produced when deducing from a dependent type.
4047///
Richard Smith30482bc2011-02-20 03:19:35 +00004048/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004049/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004050/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004051/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004052/// \param DependentDeductionDepth Set if we should permit deduction in
4053/// dependent cases. This is necessary for template partial ordering with
4054/// 'auto' template parameters. The value specified is the template
4055/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004056Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004057Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4058 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004059 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004060 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4061 if (NonPlaceholder.isInvalid())
4062 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004063 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004064 }
4065
Richard Smith87d263e2016-12-25 08:05:23 +00004066 if (!DependentDeductionDepth &&
4067 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4068 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004069 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004070 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004071 }
4072
Richard Smith87d263e2016-12-25 08:05:23 +00004073 // Find the depth of template parameter to synthesize.
4074 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4075
Richard Smith74aeef52013-04-26 16:15:35 +00004076 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4077 // Since 'decltype(auto)' can only occur at the top of the type, we
4078 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004079 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004080 if (AT->isDecltypeAuto()) {
4081 if (isa<InitListExpr>(Init)) {
4082 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4083 return DAR_FailedAlreadyDiagnosed;
4084 }
4085
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004086 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004087 if (Deduced.isNull())
4088 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004089 // FIXME: Support a non-canonical deduced type for 'auto'.
4090 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004091 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004092 if (Result.isNull())
4093 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004094 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004095 } else if (!getLangOpts().CPlusPlus) {
4096 if (isa<InitListExpr>(Init)) {
4097 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4098 return DAR_FailedAlreadyDiagnosed;
4099 }
Richard Smith74aeef52013-04-26 16:15:35 +00004100 }
4101 }
4102
Richard Smith30482bc2011-02-20 03:19:35 +00004103 SourceLocation Loc = Init->getExprLoc();
4104
4105 LocalInstantiationScope InstScope(*this);
4106
4107 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004108 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4109 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004110 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4111 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004112 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4113 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004114
Richard Smith87d263e2016-12-25 08:05:23 +00004115 QualType FuncParam =
4116 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4117 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004118 assert(!FuncParam.isNull() &&
4119 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004120
4121 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004122 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004123 Deduced.resize(1);
4124 QualType InitType = Init->getType();
4125 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004126
Richard Smith87d263e2016-12-25 08:05:23 +00004127 TemplateDeductionInfo Info(Loc, Depth);
4128
4129 // If deduction failed, don't diagnose if the initializer is dependent; it
4130 // might acquire a matching type in the instantiation.
4131 auto DeductionFailed = [&]() -> DeduceAutoResult {
4132 if (Init->isTypeDependent()) {
4133 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4134 assert(!Result.isNull() && "substituting DependentTy can't fail");
4135 return DAR_Succeeded;
4136 }
4137 return DAR_Failed;
4138 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004139
Richard Smith74801c82012-07-08 04:13:07 +00004140 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004141 if (InitList) {
4142 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004143 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4144 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004145 Info, Deduced, TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004146 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004147 }
4148 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004149 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4150 Diag(Loc, diag::err_auto_bitfield);
4151 return DAR_FailedAlreadyDiagnosed;
4152 }
4153
James Y Knight7a22b242015-08-06 20:26:32 +00004154 if (AdjustFunctionParmAndArgTypesForDeduction(
4155 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004156 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004157
James Y Knight7a22b242015-08-06 20:26:32 +00004158 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4159 FuncParam, InitType, Info, Deduced,
4160 TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004161 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004162 }
Richard Smith30482bc2011-02-20 03:19:35 +00004163
Richard Smith87d263e2016-12-25 08:05:23 +00004164 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004165 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004166 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004167
Eli Friedmane4310952012-11-06 23:56:42 +00004168 QualType DeducedType = Deduced[0].getAsType();
4169
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004170 if (InitList) {
4171 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4172 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004173 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004174 }
4175
Richard Smith061f1e22013-04-30 21:23:01 +00004176 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004177 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004178 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004179
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004180 // Check that the deduced argument type is compatible with the original
4181 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004182 if (!InitList && !Result.isNull() &&
4183 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004184 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004185 Result)) {
4186 Result = QualType();
Richard Smith87d263e2016-12-25 08:05:23 +00004187 return DeductionFailed();
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004188 }
4189
Sebastian Redl09edce02012-01-23 22:09:39 +00004190 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004191}
4192
Simon Pilgrim728134c2016-08-12 11:43:57 +00004193QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004194 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004195 if (TypeToReplaceAuto->isDependentType())
4196 TypeToReplaceAuto = QualType();
4197 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4198 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004199}
4200
Simon Pilgrim728134c2016-08-12 11:43:57 +00004201TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004202 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004203 if (TypeToReplaceAuto->isDependentType())
4204 TypeToReplaceAuto = QualType();
4205 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4206 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004207}
4208
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004209void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4210 if (isa<InitListExpr>(Init))
4211 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004212 VDecl->isInitCapture()
4213 ? diag::err_init_capture_deduction_failure_from_init_list
4214 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004215 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4216 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004217 Diag(VDecl->getLocation(),
4218 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4219 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004220 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4221 << Init->getSourceRange();
4222}
4223
Richard Smith2a7d4812013-05-04 07:00:32 +00004224bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4225 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004226 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004227
4228 if (FD->getTemplateInstantiationPattern())
4229 InstantiateFunctionDefinition(Loc, FD);
4230
Alp Toker314cc812014-01-25 16:55:45 +00004231 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004232 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4233 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4234 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4235 }
4236
4237 return StillUndeduced;
4238}
4239
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004240static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004241MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004242 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004243 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004244 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
4246/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004247static void
4248AddImplicitObjectParameterType(ASTContext &Context,
4249 CXXMethodDecl *Method,
4250 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004251 // C++11 [temp.func.order]p3:
4252 // [...] The new parameter is of type "reference to cv A," where cv are
4253 // the cv-qualifiers of the function template (if any) and A is
4254 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004255 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004256 // The standard doesn't say explicitly, but we pick the appropriate kind of
4257 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004258 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4259 ArgTy = Context.getQualifiedType(ArgTy,
4260 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004261 if (Method->getRefQualifier() == RQ_RValue)
4262 ArgTy = Context.getRValueReferenceType(ArgTy);
4263 else
4264 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004265 ArgTypes.push_back(ArgTy);
4266}
4267
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004268/// \brief Determine whether the function template \p FT1 is at least as
4269/// specialized as \p FT2.
4270static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004271 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004272 FunctionTemplateDecl *FT1,
4273 FunctionTemplateDecl *FT2,
4274 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004275 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4279 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4282 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004283 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004284 Deduced.resize(TemplateParams->size());
4285
4286 // C++0x [temp.deduct.partial]p3:
4287 // The types used to determine the ordering depend on the context in which
4288 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004289 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004290 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004291 switch (TPOC) {
4292 case TPOC_Call: {
4293 // - In the context of a function call, the function parameter types are
4294 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004295 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4296 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004297
Eli Friedman3b5774a2012-09-19 23:27:04 +00004298 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004299 // [...] If only one of the function templates is a non-static
4300 // member, that function template is considered to have a new
4301 // first parameter inserted in its function parameter list. The
4302 // new parameter is of type "reference to cv A," where cv are
4303 // the cv-qualifiers of the function template (if any) and A is
4304 // the class of which the function template is a member.
4305 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004306 // Note that we interpret this to mean "if one of the function
4307 // templates is a non-static member and the other is a non-member";
4308 // otherwise, the ordering rules for static functions against non-static
4309 // functions don't make any sense.
4310 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004311 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4312 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004313 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004314
Richard Smithe5b52202013-09-11 00:52:39 +00004315 unsigned NumComparedArguments = NumCallArguments1;
4316
4317 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004318 // Compare 'this' from Method1 against first parameter from Method2.
4319 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4320 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004321 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004322 // Compare 'this' from Method2 against first parameter from Method1.
4323 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004324 }
4325
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004326 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004327 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004328 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004329 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregorb837ea42011-01-11 17:34:58 +00004331 // C++ [temp.func.order]p5:
4332 // The presence of unused ellipsis and default arguments has no effect on
4333 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004334 if (Args1.size() > NumComparedArguments)
4335 Args1.resize(NumComparedArguments);
4336 if (Args2.size() > NumComparedArguments)
4337 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004338 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4339 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004340 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004341 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
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 case TPOC_Conversion:
4347 // - In the context of a call to a conversion operator, the return types
4348 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004349 if (DeduceTemplateArgumentsByTypeMatch(
4350 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4351 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004352 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353 return false;
4354 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004356 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004357 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004359 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4360 FD2->getType(), FD1->getType(),
4361 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004362 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004363 return false;
4364 break;
4365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004367 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368 // In most cases, all template parameters must have values in order for
4369 // deduction to succeed, but for partial ordering purposes a template
4370 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004371 // types being used for partial ordering. [ Note: a template parameter used
4372 // in a non-deduced context is considered used. -end note]
4373 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4374 for (; ArgIdx != NumArgs; ++ArgIdx)
4375 if (Deduced[ArgIdx].isNull())
4376 break;
4377
Richard Smithcf824862016-12-30 04:32:02 +00004378 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4379 // to substitute the deduced arguments back into the template and check that
4380 // we get the right type.
4381
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004382 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004384 // as FT2.
4385 return true;
4386 }
4387
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004388 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004389 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004390 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004391 case TPOC_Call:
4392 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4393 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004394 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004395 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004398 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004399 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4400 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004403 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004404 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004405 TemplateParams->getDepth(),
4406 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004407 break;
4408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004410 for (; ArgIdx != NumArgs; ++ArgIdx)
4411 // If this argument had no value deduced but was used in one of the types
4412 // used for partial ordering, then deduction fails.
4413 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4414 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004416 return true;
4417}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418
Douglas Gregorcef1a032011-01-16 16:03:23 +00004419/// \brief Determine whether this a function template whose parameter-type-list
4420/// ends with a function parameter pack.
4421static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4422 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4423 unsigned NumParams = Function->getNumParams();
4424 if (NumParams == 0)
4425 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Douglas Gregorcef1a032011-01-16 16:03:23 +00004427 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4428 if (!Last->isParameterPack())
4429 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregorcef1a032011-01-16 16:03:23 +00004431 // Make sure that no previous parameter is a parameter pack.
4432 while (--NumParams > 0) {
4433 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4434 return false;
4435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
Douglas Gregorcef1a032011-01-16 16:03:23 +00004437 return true;
4438}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
Douglas Gregorbe999392009-09-15 16:23:51 +00004440/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004441/// to the rules of function template partial ordering (C++ [temp.func.order]).
4442///
4443/// \param FT1 the first function template
4444///
4445/// \param FT2 the second function template
4446///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004447/// \param TPOC the context in which we are performing partial ordering of
4448/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004449///
Richard Smithe5b52202013-09-11 00:52:39 +00004450/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4451/// only when \c TPOC is \c TPOC_Call.
4452///
4453/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4454/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004455///
Douglas Gregorbe999392009-09-15 16:23:51 +00004456/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004457/// template is more specialized, returns NULL.
4458FunctionTemplateDecl *
4459Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4460 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004461 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004462 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004463 unsigned NumCallArguments1,
4464 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004466 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004468 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004470 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004471 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004473 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004474 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004475
Douglas Gregorcef1a032011-01-16 16:03:23 +00004476 // FIXME: This mimics what GCC implements, but doesn't match up with the
4477 // proposed resolution for core issue 692. This area needs to be sorted out,
4478 // but for now we attempt to maintain compatibility.
4479 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4480 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4481 if (Variadic1 != Variadic2)
4482 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483
Craig Topperc3ec1492014-05-26 06:22:03 +00004484 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004485}
Douglas Gregor9b146582009-07-08 20:55:45 +00004486
Douglas Gregor450f00842009-09-25 18:43:00 +00004487/// \brief Determine if the two templates are equivalent.
4488static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4489 if (T1 == T2)
4490 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Douglas Gregor450f00842009-09-25 18:43:00 +00004492 if (!T1 || !T2)
4493 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004494
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4496}
4497
4498/// \brief Retrieve the most specialized of the given function template
4499/// specializations.
4500///
John McCall58cc69d2010-01-27 01:50:18 +00004501/// \param SpecBegin the start iterator of the function template
4502/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004503///
John McCall58cc69d2010-01-27 01:50:18 +00004504/// \param SpecEnd the end iterator of the function template
4505/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004506///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004508/// diagnostic should occur.
4509///
4510/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4511/// no matching candidates.
4512///
4513/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4514/// occurs.
4515///
4516/// \param CandidateDiag partial diagnostic used for each function template
4517/// specialization that is a candidate in the ambiguous ordering. One parameter
4518/// in this diagnostic should be unbound, which will correspond to the string
4519/// describing the template arguments for the function template specialization.
4520///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004522/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004523UnresolvedSetIterator Sema::getMostSpecialized(
4524 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4525 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004526 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4527 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4528 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004529 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004530 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004531 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004532 FailedCandidates.NoteCandidates(*this, Loc);
4533 }
John McCall58cc69d2010-01-27 01:50:18 +00004534 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536
4537 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004538 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539
Douglas Gregor450f00842009-09-25 18:43:00 +00004540 // Find the function template that is better than all of the templates it
4541 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004542 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004544 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004545 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004546 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4547 FunctionTemplateDecl *Challenger
4548 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004549 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004550 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004551 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004552 Challenger)) {
4553 Best = I;
4554 BestTemplate = Challenger;
4555 }
4556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
Douglas Gregor450f00842009-09-25 18:43:00 +00004558 // Make sure that the "best" function template is more specialized than all
4559 // of the others.
4560 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004561 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4562 FunctionTemplateDecl *Challenger
4563 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004564 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004566 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004567 BestTemplate)) {
4568 Ambiguous = true;
4569 break;
4570 }
4571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregor450f00842009-09-25 18:43:00 +00004573 if (!Ambiguous) {
4574 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004575 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Douglas Gregor450f00842009-09-25 18:43:00 +00004578 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004579 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004580 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
Richard Smithb875c432013-05-04 01:51:08 +00004582 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004583 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4584 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004585 const auto *FD = cast<FunctionDecl>(*I);
4586 PD << FD << getTemplateArgumentBindingsText(
4587 FD->getPrimaryTemplate()->getTemplateParameters(),
4588 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004589 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004590 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004591 Diag((*I)->getLocation(), PD);
4592 }
Richard Smithb875c432013-05-04 01:51:08 +00004593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
John McCall58cc69d2010-01-27 01:50:18 +00004595 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004596}
4597
Richard Smith0da6dc42016-12-24 16:40:51 +00004598/// Determine whether one partial specialization, P1, is at least as
4599/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004600///
Richard Smith26b86ea2016-12-31 21:41:23 +00004601/// \tparam TemplateLikeDecl The kind of P2, which must be a
4602/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004603/// \param T1 The injected-class-name of P1 (faked for a variable template).
4604/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004605template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004606static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004607 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004608 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004609 // C++ [temp.class.order]p1:
4610 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 // specialized as the second if, given the following rewrite to two
4612 // function templates, the first function template is at least as
4613 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004614 // templates (14.6.6.2):
4615 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616 // first partial specialization and has a single function parameter
4617 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004618 // arguments of the first partial specialization, and
4619 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620 // second partial specialization and has a single function parameter
4621 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004622 // arguments of the second partial specialization.
4623 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004624 // Rather than synthesize function templates, we merely perform the
4625 // equivalent partial ordering by performing deduction directly on
4626 // the template arguments of the class template partial
4627 // specializations. This computation is slightly simpler than the
4628 // general problem of function template partial ordering, because
4629 // class template partial specializations are more constrained. We
4630 // know that every template parameter is deducible from the class
4631 // template partial specialization's template arguments, for
4632 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004633 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004634
Richard Smith0da6dc42016-12-24 16:40:51 +00004635 // Determine whether P1 is at least as specialized as P2.
4636 Deduced.resize(P2->getTemplateParameters()->size());
4637 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4638 T2, T1, Info, Deduced, TDF_None,
4639 /*PartialOrdering=*/true))
4640 return false;
4641
4642 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4643 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004644 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4645 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004646 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4647 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004648 S, P2, /*PartialOrdering=*/true,
4649 TemplateArgumentList(TemplateArgumentList::OnStack,
4650 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004651 Deduced, Info))
4652 return false;
4653
4654 return true;
4655}
4656
4657/// \brief Returns the more specialized class template partial specialization
4658/// according to the rules of partial ordering of class template partial
4659/// specializations (C++ [temp.class.order]).
4660///
4661/// \param PS1 the first class template partial specialization
4662///
4663/// \param PS2 the second class template partial specialization
4664///
4665/// \returns the more specialized class template partial specialization. If
4666/// neither partial specialization is more specialized, returns NULL.
4667ClassTemplatePartialSpecializationDecl *
4668Sema::getMoreSpecializedPartialSpecialization(
4669 ClassTemplatePartialSpecializationDecl *PS1,
4670 ClassTemplatePartialSpecializationDecl *PS2,
4671 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004672 QualType PT1 = PS1->getInjectedSpecializationType();
4673 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Richard Smith0e617ec2016-12-27 07:56:27 +00004675 TemplateDeductionInfo Info(Loc);
4676 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4677 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004678
4679 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004680 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004681
4682 return Better1 ? PS1 : PS2;
4683}
4684
Richard Smith0e617ec2016-12-27 07:56:27 +00004685bool Sema::isMoreSpecializedThanPrimary(
4686 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4687 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4688 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4689 QualType PartialT = Spec->getInjectedSpecializationType();
4690 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4691 return false;
4692 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4693 Info.clearSFINAEDiagnostic();
4694 return false;
4695 }
4696 return true;
4697}
4698
Larisse Voufo39a1e502013-08-06 01:03:05 +00004699VarTemplatePartialSpecializationDecl *
4700Sema::getMoreSpecializedPartialSpecialization(
4701 VarTemplatePartialSpecializationDecl *PS1,
4702 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004703 // Pretend the variable template specializations are class template
4704 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004705 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004706 "the partial specializations being compared should specialize"
4707 " the same template.");
4708 TemplateName Name(PS1->getSpecializedTemplate());
4709 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4710 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004711 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004712 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004713 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004714
Richard Smith0e617ec2016-12-27 07:56:27 +00004715 TemplateDeductionInfo Info(Loc);
4716 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4717 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718
Douglas Gregorbe999392009-09-15 16:23:51 +00004719 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004720 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721
Richard Smith0da6dc42016-12-24 16:40:51 +00004722 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004723}
4724
Richard Smith0e617ec2016-12-27 07:56:27 +00004725bool Sema::isMoreSpecializedThanPrimary(
4726 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4727 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4728 // FIXME: Cache the injected template arguments rather than recomputing
4729 // them for each partial specialization.
4730 SmallVector<TemplateArgument, 8> PrimaryArgs;
4731 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4732 PrimaryArgs);
4733
4734 TemplateName CanonTemplate =
4735 Context.getCanonicalTemplateName(TemplateName(Primary));
4736 QualType PrimaryT = Context.getTemplateSpecializationType(
4737 CanonTemplate, PrimaryArgs);
4738 QualType PartialT = Context.getTemplateSpecializationType(
4739 CanonTemplate, Spec->getTemplateArgs().asArray());
4740 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4741 return false;
4742 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4743 Info.clearSFINAEDiagnostic();
4744 return false;
4745 }
4746 return true;
4747}
4748
Richard Smith26b86ea2016-12-31 21:41:23 +00004749bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4750 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4751 // C++1z [temp.arg.template]p4: (DR 150)
4752 // A template template-parameter P is at least as specialized as a
4753 // template template-argument A if, given the following rewrite to two
4754 // function templates...
4755
4756 // Rather than synthesize function templates, we merely perform the
4757 // equivalent partial ordering by performing deduction directly on
4758 // the template parameter lists of the template template parameters.
4759 //
4760 // Given an invented class template X with the template parameter list of
4761 // A (including default arguments):
4762 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4763 TemplateParameterList *A = AArg->getTemplateParameters();
4764
4765 // - Each function template has a single function parameter whose type is
4766 // a specialization of X with template arguments corresponding to the
4767 // template parameters from the respective function template
4768 SmallVector<TemplateArgument, 8> AArgs;
4769 Context.getInjectedTemplateArgs(A, AArgs);
4770
4771 // Check P's arguments against A's parameter list. This will fill in default
4772 // template arguments as needed. AArgs are already correct by construction.
4773 // We can't just use CheckTemplateIdType because that will expand alias
4774 // templates.
4775 SmallVector<TemplateArgument, 4> PArgs;
4776 {
4777 SFINAETrap Trap(*this);
4778
4779 Context.getInjectedTemplateArgs(P, PArgs);
4780 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4781 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4782 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4783 // expansions, to form an "as written" argument list.
4784 TemplateArgument Arg = PArgs[I];
4785 if (Arg.getKind() == TemplateArgument::Pack) {
4786 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4787 Arg = *Arg.pack_begin();
4788 }
4789 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4790 Arg, QualType(), P->getParam(I)->getLocation()));
4791 }
4792 PArgs.clear();
4793
4794 // C++1z [temp.arg.template]p3:
4795 // If the rewrite produces an invalid type, then P is not at least as
4796 // specialized as A.
4797 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4798 Trap.hasErrorOccurred())
4799 return false;
4800 }
4801
4802 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4803 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4804
Richard Smith26b86ea2016-12-31 21:41:23 +00004805 // ... the function template corresponding to P is at least as specialized
4806 // as the function template corresponding to A according to the partial
4807 // ordering rules for function templates.
4808 TemplateDeductionInfo Info(Loc, A->getDepth());
4809 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4810}
4811
Mike Stump11289f42009-09-09 15:08:12 +00004812static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004813MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004814 const TemplateArgument &TemplateArg,
4815 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004816 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004817 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004818
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004819/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004820/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004821static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004822MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004823 const Expr *E,
4824 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004825 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004826 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004827 // We can deduce from a pack expansion.
4828 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4829 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Richard Smith34349002012-07-09 03:07:20 +00004831 // Skip through any implicit casts we added while type-checking, and any
4832 // substitutions performed by template alias expansion.
4833 while (1) {
4834 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4835 E = ICE->getSubExpr();
4836 else if (const SubstNonTypeTemplateParmExpr *Subst =
4837 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4838 E = Subst->getReplacement();
4839 else
4840 break;
4841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004842
4843 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004844 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004845 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004846 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004847 return;
4848
Mike Stump11289f42009-09-09 15:08:12 +00004849 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004850 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4851 if (!NTTP)
4852 return;
4853
Douglas Gregor21610382009-10-29 00:04:11 +00004854 if (NTTP->getDepth() == Depth)
4855 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004856
4857 // In C++1z mode, additional arguments may be deduced from the type of a
4858 // non-type argument.
4859 if (Ctx.getLangOpts().CPlusPlus1z)
4860 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004861}
4862
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004863/// \brief Mark the template parameters that are used by the given
4864/// nested name specifier.
4865static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004866MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004867 NestedNameSpecifier *NNS,
4868 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004869 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004870 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 if (!NNS)
4872 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004875 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004876 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004877 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004878}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004880/// \brief Mark the template parameters that are used by the given
4881/// template name.
4882static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004883MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004884 TemplateName Name,
4885 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004886 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004887 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004888 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4889 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004890 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4891 if (TTP->getDepth() == Depth)
4892 Used[TTP->getIndex()] = true;
4893 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004894 return;
4895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004897 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004898 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004899 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004900 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004901 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004902 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004903}
4904
4905/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004906/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004907static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004908MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004909 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004910 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004911 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004912 if (T.isNull())
4913 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914
Douglas Gregor91772d12009-06-13 00:26:55 +00004915 // Non-dependent types have nothing deducible
4916 if (!T->isDependentType())
4917 return;
4918
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004919 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004920 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004921 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004922 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004923 cast<PointerType>(T)->getPointeeType(),
4924 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004925 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004926 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004927 break;
4928
4929 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004930 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004931 cast<BlockPointerType>(T)->getPointeeType(),
4932 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004933 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004934 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004935 break;
4936
4937 case Type::LValueReference:
4938 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004939 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004940 cast<ReferenceType>(T)->getPointeeType(),
4941 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004942 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004943 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004944 break;
4945
4946 case Type::MemberPointer: {
4947 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004948 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004949 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004950 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004951 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004952 break;
4953 }
4954
4955 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004956 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004957 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004958 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004959 // Fall through to check the element type
4960
4961 case Type::ConstantArray:
4962 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004963 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004964 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004965 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004966 break;
4967
4968 case Type::Vector:
4969 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004970 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004971 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004972 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004973 break;
4974
Douglas Gregor758a8692009-06-17 21:51:59 +00004975 case Type::DependentSizedExtVector: {
4976 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004977 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004978 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004979 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004980 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004981 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004982 break;
4983 }
4984
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004986 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004987 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4988 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004989 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4990 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004991 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 break;
4993 }
4994
Douglas Gregor21610382009-10-29 00:04:11 +00004995 case Type::TemplateTypeParm: {
4996 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4997 if (TTP->getDepth() == Depth)
4998 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004999 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005000 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005001
Douglas Gregorfb322d82011-01-14 05:11:40 +00005002 case Type::SubstTemplateTypeParmPack: {
5003 const SubstTemplateTypeParmPackType *Subst
5004 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005005 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005006 QualType(Subst->getReplacedParameter(), 0),
5007 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005008 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005009 OnlyDeduced, Depth, Used);
5010 break;
5011 }
5012
John McCall2408e322010-04-27 00:57:59 +00005013 case Type::InjectedClassName:
5014 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5015 // fall through
5016
Douglas Gregor91772d12009-06-13 00:26:55 +00005017 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005018 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005019 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005020 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005021 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregord0ad2942010-12-23 01:24:45 +00005023 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005024 // If the template argument list of P contains a pack expansion that is
5025 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005026 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005028 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005029 break;
5030
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005031 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005032 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005033 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005034 break;
5035 }
5036
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005037 case Type::Complex:
5038 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005039 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005041 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005042 break;
5043
Eli Friedman0dfb8892011-10-06 23:00:33 +00005044 case Type::Atomic:
5045 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005046 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005047 cast<AtomicType>(T)->getValueType(),
5048 OnlyDeduced, Depth, Used);
5049 break;
5050
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005051 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005052 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005053 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005054 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005055 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005056 break;
5057
John McCallc392f372010-06-11 00:33:02 +00005058 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005059 // C++14 [temp.deduct.type]p5:
5060 // The non-deduced contexts are:
5061 // -- The nested-name-specifier of a type that was specified using a
5062 // qualified-id
5063 //
5064 // C++14 [temp.deduct.type]p6:
5065 // When a type name is specified in a way that includes a non-deduced
5066 // context, all of the types that comprise that type name are also
5067 // non-deduced.
5068 if (OnlyDeduced)
5069 break;
5070
John McCallc392f372010-06-11 00:33:02 +00005071 const DependentTemplateSpecializationType *Spec
5072 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Richard Smith50d5b972015-12-30 20:56:05 +00005074 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5075 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005076
John McCallc392f372010-06-11 00:33:02 +00005077 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005078 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005079 Used);
5080 break;
5081 }
5082
John McCallbd8d9bd2010-03-01 23:49:17 +00005083 case Type::TypeOf:
5084 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005085 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005086 cast<TypeOfType>(T)->getUnderlyingType(),
5087 OnlyDeduced, Depth, Used);
5088 break;
5089
5090 case Type::TypeOfExpr:
5091 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005092 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005093 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5094 OnlyDeduced, Depth, Used);
5095 break;
5096
5097 case Type::Decltype:
5098 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005099 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005100 cast<DecltypeType>(T)->getUnderlyingExpr(),
5101 OnlyDeduced, Depth, Used);
5102 break;
5103
Alexis Hunte852b102011-05-24 22:41:36 +00005104 case Type::UnaryTransform:
5105 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005106 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005107 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005108 OnlyDeduced, Depth, Used);
5109 break;
5110
Douglas Gregord2fa7662010-12-20 02:24:11 +00005111 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005112 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005113 cast<PackExpansionType>(T)->getPattern(),
5114 OnlyDeduced, Depth, Used);
5115 break;
5116
Richard Smith30482bc2011-02-20 03:19:35 +00005117 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005118 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005119 cast<AutoType>(T)->getDeducedType(),
5120 OnlyDeduced, Depth, Used);
5121
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005122 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005123 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005124 case Type::VariableArray:
5125 case Type::FunctionNoProto:
5126 case Type::Record:
5127 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005128 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005129 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005130 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005131 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005132 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005133#define TYPE(Class, Base)
5134#define ABSTRACT_TYPE(Class, Base)
5135#define DEPENDENT_TYPE(Class, Base)
5136#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5137#include "clang/AST/TypeNodes.def"
5138 break;
5139 }
5140}
5141
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005142/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005143/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005144static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005145MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005146 const TemplateArgument &TemplateArg,
5147 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005148 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005149 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005150 switch (TemplateArg.getKind()) {
5151 case TemplateArgument::Null:
5152 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005153 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005154 break;
Mike Stump11289f42009-09-09 15:08:12 +00005155
Eli Friedmanb826a002012-09-26 02:36:12 +00005156 case TemplateArgument::NullPtr:
5157 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5158 Depth, Used);
5159 break;
5160
Douglas Gregor91772d12009-06-13 00:26:55 +00005161 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005162 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005163 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005164 break;
5165
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005166 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005167 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005168 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005169 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005170 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005171 break;
5172
5173 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005174 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005175 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005176 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Anders Carlssonbc343912009-06-15 17:04:53 +00005178 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005179 for (const auto &P : TemplateArg.pack_elements())
5180 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005181 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005182 }
5183}
5184
James Dennett41725122012-06-22 10:16:05 +00005185/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005186/// template argument list.
5187///
5188/// \param TemplateArgs the template argument list from which template
5189/// parameters will be deduced.
5190///
James Dennett41725122012-06-22 10:16:05 +00005191/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005192/// to indicate when the corresponding template parameter will be
5193/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005194void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005195Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005196 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005197 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005198 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199 // If the template argument list of P contains a pack expansion that is not
5200 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005201 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005202 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005203 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005204 return;
5205
Douglas Gregor91772d12009-06-13 00:26:55 +00005206 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005207 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005208 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005209}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005210
5211/// \brief Marks all of the template parameters that will be deduced by a
5212/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005213void Sema::MarkDeducedTemplateParameters(
5214 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5215 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005216 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005217 = FunctionTemplate->getTemplateParameters();
5218 Deduced.clear();
5219 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005220
Douglas Gregorce23bae2009-09-18 23:21:38 +00005221 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5222 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005223 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005224 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005225}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005226
5227bool hasDeducibleTemplateParameters(Sema &S,
5228 FunctionTemplateDecl *FunctionTemplate,
5229 QualType T) {
5230 if (!T->isDependentType())
5231 return false;
5232
5233 TemplateParameterList *TemplateParams
5234 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005235 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005236 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005237 Deduced);
5238
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005239 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005240}