blob: 0bc85a2f2635bd68c05ce96d5f6638a9a0ae9605 [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.
Renato Golindad96d62017-01-02 11:15:42 +00002852Sema::TemplateDeductionResult
2853Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2854 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2855 unsigned NumExplicitlySpecified,
2856 FunctionDecl *&Specialization,
2857 TemplateDeductionInfo &Info,
2858 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2859 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002860 // Unevaluated SFINAE context.
2861 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002862 SFINAETrap Trap(*this);
2863
Douglas Gregor9b146582009-07-08 20:55:45 +00002864 // Enter a new template instantiation context while we instantiate the
2865 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002866 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002867 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2868 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002869 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2870 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002871 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002872 return TDK_InstantiationDepth;
2873
John McCalle23b8712010-04-29 01:18:58 +00002874 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002875
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002876 // C++ [temp.deduct.type]p2:
2877 // [...] or if any template argument remains neither deduced nor
2878 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002879 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002880 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002881 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002882 CurrentInstantiationScope, NumExplicitlySpecified,
2883 PartialOverloading))
2884 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002885
2886 // Form the template argument list from the deduced template arguments.
2887 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002888 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002889 Info.reset(DeducedArgumentList);
2890
Mike Stump11289f42009-09-09 15:08:12 +00002891 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002892 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002893 DeclContext *Owner = FunctionTemplate->getDeclContext();
2894 if (FunctionTemplate->getFriendObjectKind())
2895 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002896 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002897 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002898 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002899 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002900 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002901
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002903 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904
Mike Stump11289f42009-09-09 15:08:12 +00002905 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002906 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002907 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2908 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002909 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002910
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002911 // There may have been an error that did not prevent us from constructing a
2912 // declaration. Mark the declaration invalid and return with a substitution
2913 // failure.
2914 if (Trap.hasErrorOccurred()) {
2915 Specialization->setInvalidDecl(true);
2916 return TDK_SubstitutionFailure;
2917 }
2918
Douglas Gregore65aacb2011-06-16 16:50:48 +00002919 if (OriginalCallArgs) {
2920 // C++ [temp.deduct.call]p4:
2921 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002922 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002923 // is transformed as described above). [...]
2924 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2925 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002926 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002927
Douglas Gregore65aacb2011-06-16 16:50:48 +00002928 if (ParamIdx >= Specialization->getNumParams())
2929 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002930
Douglas Gregore65aacb2011-06-16 16:50:48 +00002931 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002932 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2933 Info.FirstArg = TemplateArgument(DeducedA);
2934 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2935 Info.CallArgIndex = OriginalArg.ArgIdx;
2936 return TDK_DeducedMismatch;
2937 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002938 }
2939 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002940
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002941 // If we suppressed any diagnostics while performing template argument
2942 // deduction, and if we haven't already instantiated this declaration,
2943 // keep track of these diagnostics. They'll be emitted if this specialization
2944 // is actually used.
2945 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002946 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002947 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2948 if (Pos == SuppressedDiagnostics.end())
2949 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2950 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002952
Mike Stump11289f42009-09-09 15:08:12 +00002953 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002954}
2955
John McCall8d08b9b2010-08-27 09:08:28 +00002956/// Gets the type of a function for template-argument-deducton
2957/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002958static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002959 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002960 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002961 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002962 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002963 return QualType();
2964
John McCallc1f69982010-02-02 02:21:27 +00002965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002966 if (Method->isInstance()) {
2967 // An instance method that's referenced in a form that doesn't
2968 // look like a member pointer is just invalid.
2969 if (!R.HasFormOfMemberPointer) return QualType();
2970
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 return S.Context.getMemberPointerType(Fn->getType(),
2972 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002973 }
2974
2975 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002976 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002977}
2978
2979/// Apply the deduction rules for overload sets.
2980///
2981/// \return the null type if this argument should be treated as an
2982/// undeduced context
2983static QualType
2984ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002985 Expr *Arg, QualType ParamType,
2986 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987
John McCall8d08b9b2010-08-27 09:08:28 +00002988 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002989
John McCall8d08b9b2010-08-27 09:08:28 +00002990 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002991
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002992 // C++0x [temp.deduct.call]p4
2993 unsigned TDF = 0;
2994 if (ParamWasReference)
2995 TDF |= TDF_ParamWithReferenceType;
2996 if (R.IsAddressOfOperand)
2997 TDF |= TDF_IgnoreQualifiers;
2998
John McCallc1f69982010-02-02 02:21:27 +00002999 // C++0x [temp.deduct.call]p6:
3000 // When P is a function type, pointer to function type, or pointer
3001 // to member function type:
3002
3003 if (!ParamType->isFunctionType() &&
3004 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003005 !ParamType->isMemberFunctionPointerType()) {
3006 if (Ovl->hasExplicitTemplateArgs()) {
3007 // But we can still look for an explicit specialization.
3008 if (FunctionDecl *ExplicitSpec
3009 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003010 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003011 }
John McCallc1f69982010-02-02 02:21:27 +00003012
George Burgess IVcc2f3552016-03-19 21:51:45 +00003013 DeclAccessPair DAP;
3014 if (FunctionDecl *Viable =
3015 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3016 return GetTypeOfFunction(S, R, Viable);
3017
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003018 return QualType();
3019 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003020
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003021 // Gather the explicit template arguments, if any.
3022 TemplateArgumentListInfo ExplicitTemplateArgs;
3023 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003024 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003025 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003026 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3027 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003028 NamedDecl *D = (*I)->getUnderlyingDecl();
3029
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003030 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3031 // - If the argument is an overload set containing one or more
3032 // function templates, the parameter is treated as a
3033 // non-deduced context.
3034 if (!Ovl->hasExplicitTemplateArgs())
3035 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003036
3037 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003038 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003039 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003040 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3041 Specialization, Info))
3042 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003043
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003044 D = Specialization;
3045 }
John McCallc1f69982010-02-02 02:21:27 +00003046
3047 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003048 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003049 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003050
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003051 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003053 ArgType->isFunctionType())
3054 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055
John McCallc1f69982010-02-02 02:21:27 +00003056 // - If the argument is an overload set (not containing function
3057 // templates), trial argument deduction is attempted using each
3058 // of the members of the set. If deduction succeeds for only one
3059 // of the overload set members, that member is used as the
3060 // argument value for the deduction. If deduction succeeds for
3061 // more than one member of the overload set the parameter is
3062 // treated as a non-deduced context.
3063
3064 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3065 // Type deduction is done independently for each P/A pair, and
3066 // the deduced template argument values are then combined.
3067 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003068 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003069 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003070 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003071 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003072 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3073 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003074 if (Result) continue;
3075 if (!Match.isNull()) return QualType();
3076 Match = ArgType;
3077 }
3078
3079 return Match;
3080}
3081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003083/// described in C++ [temp.deduct.call].
3084///
3085/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003086/// argument deduction based on this P/A pair because the argument is an
3087/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003088static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3089 TemplateParameterList *TemplateParams,
3090 QualType &ParamType,
3091 QualType &ArgType,
3092 Expr *Arg,
3093 unsigned &TDF) {
3094 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003095 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003096 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003097 if (ParamType.hasQualifiers())
3098 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003099
3100 // [...] If P is a reference type, the type referred to by P is
3101 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003102 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003103 if (ParamRefType)
3104 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003105
Nathan Sidwell96090022015-01-16 15:20:14 +00003106 // Overload sets usually make this parameter an undeduced context,
3107 // but there are sometimes special circumstances. Typically
3108 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003109 if (ArgType == S.Context.OverloadTy) {
3110 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3111 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003112 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003113 if (ArgType.isNull())
3114 return true;
3115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
Douglas Gregor7825bf32011-01-06 22:09:01 +00003117 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003118 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003119 if (ArgType->isIncompleteArrayType()) {
3120 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003121 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003122 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003123
Douglas Gregor7825bf32011-01-06 22:09:01 +00003124 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003125 // If P is an rvalue reference to a cv-unqualified template
3126 // parameter and the argument is an lvalue, the type "lvalue
3127 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003128 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003129 !ParamType.getQualifiers() &&
3130 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003131 Arg->isLValue())
3132 ArgType = S.Context.getLValueReferenceType(ArgType);
3133 } else {
3134 // C++ [temp.deduct.call]p2:
3135 // If P is not a reference type:
3136 // - If A is an array type, the pointer type produced by the
3137 // array-to-pointer standard conversion (4.2) is used in place of
3138 // A for type deduction; otherwise,
3139 if (ArgType->isArrayType())
3140 ArgType = S.Context.getArrayDecayedType(ArgType);
3141 // - If A is a function type, the pointer type produced by the
3142 // function-to-pointer standard conversion (4.3) is used in place
3143 // of A for type deduction; otherwise,
3144 else if (ArgType->isFunctionType())
3145 ArgType = S.Context.getPointerType(ArgType);
3146 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003147 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003148 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003149 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003150 }
3151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Douglas Gregor7825bf32011-01-06 22:09:01 +00003153 // C++0x [temp.deduct.call]p4:
3154 // In general, the deduction process attempts to find template argument
3155 // values that will make the deduced A identical to A (after the type A
3156 // is transformed as described above). [...]
3157 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 // - If the original P is a reference type, the deduced A (i.e., the
3160 // type referred to by the reference) can be more cv-qualified than
3161 // the transformed A.
3162 if (ParamRefType)
3163 TDF |= TDF_ParamWithReferenceType;
3164 // - The transformed A can be another pointer or pointer to member
3165 // type that can be converted to the deduced A via a qualification
3166 // conversion (4.4).
3167 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3168 ArgType->isObjCObjectPointerType())
3169 TDF |= TDF_IgnoreQualifiers;
3170 // - If P is a class and P has the form simple-template-id, then the
3171 // transformed A can be a derived class of the deduced A. Likewise,
3172 // if P is a pointer to a class of the form simple-template-id, the
3173 // transformed A can be a pointer to a derived class pointed to by
3174 // the deduced A.
3175 if (isSimpleTemplateIdType(ParamType) ||
3176 (isa<PointerType>(ParamType) &&
3177 isSimpleTemplateIdType(
3178 ParamType->getAs<PointerType>()->getPointeeType())))
3179 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Douglas Gregor7825bf32011-01-06 22:09:01 +00003181 return false;
3182}
3183
Nico Weberc153d242014-07-28 00:02:09 +00003184static bool
3185hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3186 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003187
Hubert Tong3280b332015-06-25 00:25:49 +00003188static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3189 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3190 Expr *Arg, TemplateDeductionInfo &Info,
3191 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3192
3193/// \brief Attempt template argument deduction from an initializer list
3194/// deemed to be an argument in a function call.
3195static bool
3196DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3197 QualType AdjustedParamType, InitListExpr *ILE,
3198 TemplateDeductionInfo &Info,
3199 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3200 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003201
3202 // [temp.deduct.call] p1 (post CWG-1591)
3203 // If removing references and cv-qualifiers from P gives
3204 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3205 // non-empty initializer list (8.5.4), then deduction is performed instead for
3206 // each element of the initializer list, taking P0 as a function template
3207 // parameter type and the initializer element as its argument, and in the
3208 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3209 // length of the initializer list. Otherwise, an initializer list argument
3210 // causes the parameter to be considered a non-deduced context
3211
3212 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3213
3214 const bool IsDependentSizedArray =
3215 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3216
Faisal Validd76cc12015-12-10 12:29:11 +00003217 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003218
3219 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3220 S.isStdInitializerList(AdjustedParamType, &ElTy);
3221
3222 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003223 return false;
3224
3225 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003226 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3227 // deduce against the 'T' in T[N].
3228 if (ElTy.isNull()) {
3229 assert(!IsSTDList);
3230 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003231 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003232 // Deduction only needs to be done for dependent types.
3233 if (ElTy->isDependentType()) {
3234 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003235 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3236 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003237 return true;
3238 }
3239 }
3240 if (IsDependentSizedArray) {
3241 const DependentSizedArrayType *ArrTy =
3242 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3243 // Determine the array bound is something we can deduce.
3244 if (NonTypeTemplateParmDecl *NTTP =
Richard Smith87d263e2016-12-25 08:05:23 +00003245 getDeducedParameterFromExpr(Info, ArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003246 // We can perform template argument deduction for the given non-type
3247 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003248 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3249 ILE->getNumInits());
Faisal Valif6dfdb32015-12-10 05:36:39 +00003250 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003251 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003252 /*ArrayBound=*/true, Info, Deduced);
3253 }
3254 }
Hubert Tong3280b332015-06-25 00:25:49 +00003255 return true;
3256}
3257
Sebastian Redl19181662012-03-15 21:40:51 +00003258/// \brief Perform template argument deduction by matching a parameter type
3259/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003260/// an initializer list that was originally matched against a parameter
3261/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003262static Sema::TemplateDeductionResult
3263DeduceTemplateArgumentByListElement(Sema &S,
3264 TemplateParameterList *TemplateParams,
3265 QualType ParamType, Expr *Arg,
3266 TemplateDeductionInfo &Info,
3267 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3268 unsigned TDF) {
3269 // Handle the case where an init list contains another init list as the
3270 // element.
3271 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003272 Sema::TemplateDeductionResult Result;
3273 if (!DeduceFromInitializerList(S, TemplateParams,
3274 ParamType.getNonReferenceType(), ILE, Info,
3275 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003276 return Sema::TDK_Success; // Just ignore this expression.
3277
Hubert Tong3280b332015-06-25 00:25:49 +00003278 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003279 }
3280
3281 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003282 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003283 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003284 ArgType, Arg, TDF)) {
3285 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003286 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003287 }
Sebastian Redl19181662012-03-15 21:40:51 +00003288 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003289 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003290}
3291
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003292/// \brief Perform template argument deduction from a function call
3293/// (C++ [temp.deduct.call]).
3294///
3295/// \param FunctionTemplate the function template for which we are performing
3296/// template argument deduction.
3297///
James Dennett18348b62012-06-22 08:52:37 +00003298/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003299/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003300///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003301/// \param Args the function call arguments
3302///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003304/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003305/// template argument deduction.
3306///
3307/// \param Info the argument will be updated to provide additional information
3308/// about template argument deduction.
3309///
3310/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003311Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3312 FunctionTemplateDecl *FunctionTemplate,
3313 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003314 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Renato Golindad96d62017-01-02 11:15:42 +00003315 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003316 if (FunctionTemplate->isInvalidDecl())
3317 return TDK_Invalid;
3318
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003319 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003320 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003321
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322 // C++ [temp.deduct.call]p1:
3323 // Template argument deduction is done by comparing each function template
3324 // parameter type (call it P) with the type of the corresponding argument
3325 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003326 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003327 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003328 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003329 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003330 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003331 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003332 if (Proto->isTemplateVariadic())
3333 /* Do nothing */;
3334 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003335 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003337 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor89026b52009-06-30 23:57:56 +00003340 // The types of the parameters from which we will perform template argument
3341 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003342 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003343 TemplateParameterList *TemplateParams
3344 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003345 SmallVector<DeducedTemplateArgument, 4> Deduced;
3346 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003347 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003348 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003349 TemplateDeductionResult Result =
3350 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003351 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003352 Deduced,
3353 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003354 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003355 Info);
3356 if (Result)
3357 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003358
3359 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003360 } else {
3361 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003362 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003363 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3364 }
Mike Stump11289f42009-09-09 15:08:12 +00003365
Douglas Gregor89026b52009-06-30 23:57:56 +00003366 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003367 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003368 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003369 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003370 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3371 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003372 QualType OrigParamType = ParamTypes[ParamIdx];
3373 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003374
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003376 = dyn_cast<PackExpansionType>(ParamType);
3377 if (!ParamExpansion) {
3378 // Simple case: matching a function parameter to a function argument.
3379 if (ArgIdx >= CheckArgs)
3380 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
Douglas Gregor7825bf32011-01-06 22:09:01 +00003382 Expr *Arg = Args[ArgIdx++];
3383 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003384
Douglas Gregor7825bf32011-01-06 22:09:01 +00003385 unsigned TDF = 0;
3386 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3387 ParamType, ArgType, Arg,
3388 TDF))
3389 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor0c83c812011-10-09 22:06:46 +00003391 // If we have nothing to deduce, we're done.
3392 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3393 continue;
3394
Sebastian Redl43144e72012-01-17 22:49:58 +00003395 // If the argument is an initializer list ...
3396 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003397 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003398 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003399 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3400 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003401 continue;
3402
Hubert Tong3280b332015-06-25 00:25:49 +00003403 if (Result)
3404 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003405 // Don't track the argument type, since an initializer list has none.
3406 continue;
3407 }
3408
Douglas Gregore65aacb2011-06-16 16:50:48 +00003409 // Keep track of the argument type and corresponding parameter index,
3410 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003411 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003412 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003413
Douglas Gregor7825bf32011-01-06 22:09:01 +00003414 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003415 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3416 ParamType, ArgType,
3417 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003418 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003419
Douglas Gregor7825bf32011-01-06 22:09:01 +00003420 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
Douglas Gregor7825bf32011-01-06 22:09:01 +00003423 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 // For a function parameter pack that occurs at the end of the
3425 // parameter-declaration-list, the type A of each remaining argument of
3426 // the call is compared with the type P of the declarator-id of the
3427 // function parameter pack. Each comparison deduces template arguments
3428 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003429 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003431 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003432 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003433 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434
Douglas Gregor7825bf32011-01-06 22:09:01 +00003435 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003436 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3437 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregor7825bf32011-01-06 22:09:01 +00003439 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003440 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003441 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Douglas Gregore65aacb2011-06-16 16:50:48 +00003443 QualType OrigParamType = ParamPattern;
3444 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003445 Expr *Arg = Args[ArgIdx];
3446 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003447
Douglas Gregor7825bf32011-01-06 22:09:01 +00003448 unsigned TDF = 0;
3449 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3450 ParamType, ArgType, Arg,
3451 TDF)) {
3452 // We can't actually perform any deduction for this argument, so stop
3453 // deduction at this point.
3454 ++ArgIdx;
3455 break;
3456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Sebastian Redl43144e72012-01-17 22:49:58 +00003458 // As above, initializer lists need special handling.
3459 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003460 TemplateDeductionResult Result;
3461 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3462 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003463 ++ArgIdx;
3464 break;
3465 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003466
Hubert Tong3280b332015-06-25 00:25:49 +00003467 if (Result)
3468 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003469 } else {
3470
3471 // Keep track of the argument type and corresponding argument index,
3472 // so we can check for compatibility between the deduced A and A.
3473 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003474 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003475 ArgType));
3476
3477 if (TemplateDeductionResult Result
3478 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3479 ParamType, ArgType, Info,
3480 Deduced, TDF))
3481 return Result;
3482 }
Mike Stump11289f42009-09-09 15:08:12 +00003483
Richard Smith0a80d572014-05-29 01:12:14 +00003484 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486
Douglas Gregor7825bf32011-01-06 22:09:01 +00003487 // Build argument packs for each of the parameter packs expanded by this
3488 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003489 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregor7825bf32011-01-06 22:09:01 +00003492 // After we've matching against a parameter pack, we're done.
3493 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003494 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003495
Mike Stump11289f42009-09-09 15:08:12 +00003496 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003497 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003498 Info, &OriginalCallArgs,
Renato Golindad96d62017-01-02 11:15:42 +00003499 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003500}
3501
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003502QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003503 QualType FunctionType,
3504 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003505 if (ArgFunctionType.isNull())
3506 return ArgFunctionType;
3507
3508 const FunctionProtoType *FunctionTypeP =
3509 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003510 const FunctionProtoType *ArgFunctionTypeP =
3511 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003512
3513 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3514 bool Rebuild = false;
3515
3516 CallingConv CC = FunctionTypeP->getCallConv();
3517 if (EPI.ExtInfo.getCC() != CC) {
3518 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3519 Rebuild = true;
3520 }
3521
3522 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3523 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3524 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3525 Rebuild = true;
3526 }
3527
3528 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3529 ArgFunctionTypeP->hasExceptionSpec())) {
3530 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3531 Rebuild = true;
3532 }
3533
3534 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003535 return ArgFunctionType;
3536
Richard Smithbaa47832016-12-01 02:11:49 +00003537 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3538 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003539}
3540
Douglas Gregor9b146582009-07-08 20:55:45 +00003541/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003542/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3543/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003544///
3545/// \param FunctionTemplate the function template for which we are performing
3546/// template argument deduction.
3547///
James Dennett18348b62012-06-22 08:52:37 +00003548/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003549/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003550///
3551/// \param ArgFunctionType the function type that will be used as the
3552/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003553/// function template's function type. This type may be NULL, if there is no
3554/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003555///
3556/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003557/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003558/// template argument deduction.
3559///
3560/// \param Info the argument will be updated to provide additional information
3561/// about template argument deduction.
3562///
Richard Smithbaa47832016-12-01 02:11:49 +00003563/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3564/// the address of a function template per [temp.deduct.funcaddr] and
3565/// [over.over]. If \c false, we are looking up a function template
3566/// specialization based on its signature, per [temp.deduct.decl].
3567///
Douglas Gregor9b146582009-07-08 20:55:45 +00003568/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003569Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3570 FunctionTemplateDecl *FunctionTemplate,
3571 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3572 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3573 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003574 if (FunctionTemplate->isInvalidDecl())
3575 return TDK_Invalid;
3576
Douglas Gregor9b146582009-07-08 20:55:45 +00003577 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3578 TemplateParameterList *TemplateParams
3579 = FunctionTemplate->getTemplateParameters();
3580 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003581
3582 // When taking the address of a function, we require convertibility of
3583 // the resulting function type. Otherwise, we allow arbitrary mismatches
3584 // of calling convention, noreturn, and noexcept.
3585 if (!IsAddressOfFunction)
3586 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3587 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003588
Douglas Gregor9b146582009-07-08 20:55:45 +00003589 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003590 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003591 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003592 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003593 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003594 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003595 if (TemplateDeductionResult Result
3596 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003597 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003598 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003599 &FunctionType, Info))
3600 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003601
3602 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003603 }
3604
Eli Friedman77dcc722012-02-08 03:07:05 +00003605 // Unevaluated SFINAE context.
3606 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003607 SFINAETrap Trap(*this);
3608
John McCallc1f69982010-02-02 02:21:27 +00003609 Deduced.resize(TemplateParams->size());
3610
Richard Smith2a7d4812013-05-04 07:00:32 +00003611 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003612 // type so that we treat it as a non-deduced context in what follows. If we
3613 // are looking up by signature, the signature type should also have a deduced
3614 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003615 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003616 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003617 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003618 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003619 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003620 }
3621
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003622 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003623 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003624 if (IsAddressOfFunction)
3625 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003626 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003627 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003628 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003629 FunctionType, ArgFunctionType,
3630 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003631 return Result;
3632 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003633
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003635 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3636 NumExplicitlySpecified,
3637 Specialization, Info))
3638 return Result;
3639
Richard Smith2a7d4812013-05-04 07:00:32 +00003640 // If the function has a deduced return type, deduce it now, so we can check
3641 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003642 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003643 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003644 DeduceReturnType(Specialization, Info.getLocation(), false))
3645 return TDK_MiscellaneousDeductionFailure;
3646
Richard Smith9095e5b2016-11-01 01:31:23 +00003647 // If the function has a dependent exception specification, resolve it now,
3648 // so we can check that the exception specification matches.
3649 auto *SpecializationFPT =
3650 Specialization->getType()->castAs<FunctionProtoType>();
3651 if (getLangOpts().CPlusPlus1z &&
3652 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3653 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3654 return TDK_MiscellaneousDeductionFailure;
3655
Richard Smithbaa47832016-12-01 02:11:49 +00003656 // Adjust the exception specification of the argument again to match the
3657 // substituted and resolved type we just formed. (Calling convention and
3658 // noreturn can't be dependent, so we don't actually need this for them
3659 // right now.)
3660 QualType SpecializationType = Specialization->getType();
3661 if (!IsAddressOfFunction)
3662 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3663 /*AdjustExceptionSpec*/true);
3664
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003665 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003666 // specialization with respect to arguments of compatible pointer to function
3667 // types, template argument deduction fails.
3668 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003669 if (IsAddressOfFunction &&
3670 !isSameOrCompatibleFunctionType(
3671 Context.getCanonicalType(SpecializationType),
3672 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003673 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003674
3675 if (!IsAddressOfFunction &&
3676 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003677 return TDK_MiscellaneousDeductionFailure;
3678 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003679
3680 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003681}
3682
Simon Pilgrim728134c2016-08-12 11:43:57 +00003683/// \brief Given a function declaration (e.g. a generic lambda conversion
3684/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003685/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3686/// to replace 'auto' with and not the actual result type you want
3687/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003688static inline void
3689SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003690 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003691 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003692 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003693 assert(AutoResultType->getContainedAutoType());
3694 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003695 TypeToReplaceAutoWith);
3696 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3697}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003698
Simon Pilgrim728134c2016-08-12 11:43:57 +00003699/// \brief Given a specialized conversion operator of a generic lambda
3700/// create the corresponding specializations of the call operator and
3701/// the static-invoker. If the return type of the call operator is auto,
3702/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003703/// return type of the destination function ptr.
3704
Simon Pilgrim728134c2016-08-12 11:43:57 +00003705static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003706SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3707 CXXConversionDecl *ConversionSpecialized,
3708 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3709 QualType ReturnTypeOfDestFunctionPtr,
3710 TemplateDeductionInfo &TDInfo,
3711 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003712
Faisal Vali2b3a3012013-10-24 23:40:02 +00003713 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003714 assert(LambdaClass && LambdaClass->isGenericLambda());
3715
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003717 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003718 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003719 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003720
3721 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003722 CallOpGeneric->getDescribedFunctionTemplate();
3723
Craig Topperc3ec1492014-05-26 06:22:03 +00003724 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003725 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 // generic lambda's call operator.
3727 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003728 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3729 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003730 0, CallOpSpecialized, TDInfo))
3731 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732
Faisal Vali2b3a3012013-10-24 23:40:02 +00003733 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003734 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3735 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003736 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 CallOpSpecialized->getPointOfInstantiation(),
3738 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003739
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 // Check to see if the return type of the destination ptr-to-function
3741 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003742 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003743 ReturnTypeOfDestFunctionPtr))
3744 return Sema::TDK_NonDeducedMismatch;
3745 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003746 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003747 // specialized our corresponding call operator, we are ready to
3748 // specialize the static invoker with the deduced arguments of our
3749 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003750 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3752 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3753
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003754#ifndef NDEBUG
3755 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3756#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003757 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003758 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003759 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003760 "If the call operator succeeded so should the invoker!");
3761 // Set the result type to match the corresponding call operator
3762 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003763 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3764 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003765 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003766 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003767 // to substitute into the 'auto' of the invoker and conversion
3768 // function.
3769 // For e.g.
3770 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3771 // We don't want to subst 'int*' into 'auto' to get int**.
3772
Alp Toker314cc812014-01-25 16:55:45 +00003773 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3774 ->getContainedAutoType()
3775 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3777 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003778 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003779 TypeToReplaceAutoWith, S);
3780 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003781
Faisal Vali2b3a3012013-10-24 23:40:02 +00003782 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003783 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003784 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003785 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3787 getType().getTypePtr()->castAs<FunctionProtoType>();
3788 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3789 EPI.TypeQuals = 0;
3790 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003791 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003792 return Sema::TDK_Success;
3793}
Douglas Gregor05155d82009-08-21 23:19:43 +00003794/// \brief Deduce template arguments for a templated conversion
3795/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3796/// conversion function template specialization.
3797Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003798Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003799 QualType ToType,
3800 CXXConversionDecl *&Specialization,
3801 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003802 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003803 return TDK_Invalid;
3804
Faisal Vali2b3a3012013-10-24 23:40:02 +00003805 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003806 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3807
Faisal Vali2b3a3012013-10-24 23:40:02 +00003808 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003809
3810 // Canonicalize the types for deduction.
3811 QualType P = Context.getCanonicalType(FromType);
3812 QualType A = Context.getCanonicalType(ToType);
3813
Douglas Gregord99609a2011-03-06 09:03:20 +00003814 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003815 // If P is a reference type, the type referred to by P is used for
3816 // type deduction.
3817 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3818 P = PRef->getPointeeType();
3819
Douglas Gregord99609a2011-03-06 09:03:20 +00003820 // C++0x [temp.deduct.conv]p4:
3821 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003822 // for type deduction.
3823 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003824 A = ARef->getPointeeType().getUnqualifiedType();
3825 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003826 //
Mike Stump11289f42009-09-09 15:08:12 +00003827 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003828 else {
3829 assert(!A->isReferenceType() && "Reference types were handled above");
3830
3831 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003832 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003833 // of P for type deduction; otherwise,
3834 if (P->isArrayType())
3835 P = Context.getArrayDecayedType(P);
3836 // - If P is a function type, the pointer type produced by the
3837 // function-to-pointer standard conversion (4.3) is used in
3838 // place of P for type deduction; otherwise,
3839 else if (P->isFunctionType())
3840 P = Context.getPointerType(P);
3841 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003842 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003843 else
3844 P = P.getUnqualifiedType();
3845
Douglas Gregord99609a2011-03-06 09:03:20 +00003846 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003847 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003848 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003849 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003850 A = A.getUnqualifiedType();
3851 }
3852
Eli Friedman77dcc722012-02-08 03:07:05 +00003853 // Unevaluated SFINAE context.
3854 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003855 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003856
3857 // C++ [temp.deduct.conv]p1:
3858 // Template argument deduction is done by comparing the return
3859 // type of the template conversion function (call it P) with the
3860 // type that is required as the result of the conversion (call it
3861 // A) as described in 14.8.2.4.
3862 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003863 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003864 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003865 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003866
3867 // C++0x [temp.deduct.conv]p4:
3868 // In general, the deduction process attempts to find template
3869 // argument values that will make the deduced A identical to
3870 // A. However, there are two cases that allow a difference:
3871 unsigned TDF = 0;
3872 // - If the original A is a reference type, A can be more
3873 // cv-qualified than the deduced A (i.e., the type referred to
3874 // by the reference)
3875 if (ToType->isReferenceType())
3876 TDF |= TDF_ParamWithReferenceType;
3877 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003878 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003879 // conversion.
3880 //
3881 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3882 // both P and A are pointers or member pointers. In this case, we
3883 // just ignore cv-qualifiers completely).
3884 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003885 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003886 TDF |= TDF_IgnoreQualifiers;
3887 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003888 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3889 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003890 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003891
3892 // Create an Instantiation Scope for finalizing the operator.
3893 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003894 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003895 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003896 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003897 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003898 ConversionSpecialized, Info);
3899 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3900
3901 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003902 // to a ptr-to-function, use the deduced arguments from the conversion
3903 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003904 // e.g., int (*fp)(int) = [](auto a) { return a; };
3905 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003906
Faisal Vali2b3a3012013-10-24 23:40:02 +00003907 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003908 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003909 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003910 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003911 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003912 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003913 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003914 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3915
Simon Pilgrim728134c2016-08-12 11:43:57 +00003916 // Create the corresponding specializations of the call operator and
3917 // the static-invoker; and if the return type is auto,
3918 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003919 // DestFunctionPtrReturnType.
3920 // For instance:
3921 // auto L = [](auto a) { return f(a); };
3922 // int (*fp)(int) = L;
3923 // char (*fp2)(int) = L; <-- Not OK.
3924
3925 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003926 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003927 Info, *this);
3928 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003929 return Result;
3930}
3931
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003932/// \brief Deduce template arguments for a function template when there is
3933/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3934///
3935/// \param FunctionTemplate the function template for which we are performing
3936/// template argument deduction.
3937///
James Dennett18348b62012-06-22 08:52:37 +00003938/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003939/// arguments.
3940///
3941/// \param Specialization if template argument deduction was successful,
3942/// this will be set to the function template specialization produced by
3943/// template argument deduction.
3944///
3945/// \param Info the argument will be updated to provide additional information
3946/// about template argument deduction.
3947///
Richard Smithbaa47832016-12-01 02:11:49 +00003948/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3949/// the address of a function template in a context where we do not have a
3950/// target type, per [over.over]. If \c false, we are looking up a function
3951/// template specialization based on its signature, which only happens when
3952/// deducing a function parameter type from an argument that is a template-id
3953/// naming a function template specialization.
3954///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003955/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003956Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3957 FunctionTemplateDecl *FunctionTemplate,
3958 TemplateArgumentListInfo *ExplicitTemplateArgs,
3959 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3960 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003961 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003962 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003963 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003964}
3965
Richard Smith30482bc2011-02-20 03:19:35 +00003966namespace {
3967 /// Substitute the 'auto' type specifier within a type for a given replacement
3968 /// type.
3969 class SubstituteAutoTransform :
3970 public TreeTransform<SubstituteAutoTransform> {
3971 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003972 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003973 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003974 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3975 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003976 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003977 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003978
Richard Smith30482bc2011-02-20 03:19:35 +00003979 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3980 // If we're building the type pattern to deduce against, don't wrap the
3981 // substituted type in an AutoType. Certain template deduction rules
3982 // apply only when a template type parameter appears directly (and not if
3983 // the parameter is found through desugaring). For instance:
3984 // auto &&lref = lvalue;
3985 // must transform into "rvalue reference to T" not "rvalue reference to
3986 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003987 if (!UseAutoSugar) {
3988 assert(isa<TemplateTypeParmType>(Replacement) &&
3989 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003990 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003991 TemplateTypeParmTypeLoc NewTL =
3992 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003993 NewTL.setNameLoc(TL.getNameLoc());
3994 return Result;
3995 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00003996 QualType Result = SemaRef.Context.getAutoType(
3997 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003998 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3999 NewTL.setNameLoc(TL.getNameLoc());
4000 return Result;
4001 }
4002 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004003
4004 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4005 // Lambdas never need to be transformed.
4006 return E;
4007 }
Richard Smith061f1e22013-04-30 21:23:01 +00004008
Richard Smith2a7d4812013-05-04 07:00:32 +00004009 QualType Apply(TypeLoc TL) {
4010 // Create some scratch storage for the transformed type locations.
4011 // FIXME: We're just going to throw this information away. Don't build it.
4012 TypeLocBuilder TLB;
4013 TLB.reserve(TL.getFullDataSize());
4014 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004015 }
Richard Smith30482bc2011-02-20 03:19:35 +00004016 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004017}
Richard Smith30482bc2011-02-20 03:19:35 +00004018
Richard Smith2a7d4812013-05-04 07:00:32 +00004019Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004020Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4021 Optional<unsigned> DependentDeductionDepth) {
4022 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4023 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004024}
4025
Richard Smith061f1e22013-04-30 21:23:01 +00004026/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004027///
Richard Smith87d263e2016-12-25 08:05:23 +00004028/// Note that this is done even if the initializer is dependent. (This is
4029/// necessary to support partial ordering of templates using 'auto'.)
4030/// A dependent type will be produced when deducing from a dependent type.
4031///
Richard Smith30482bc2011-02-20 03:19:35 +00004032/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004033/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004034/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004035/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004036/// \param DependentDeductionDepth Set if we should permit deduction in
4037/// dependent cases. This is necessary for template partial ordering with
4038/// 'auto' template parameters. The value specified is the template
4039/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004040Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004041Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4042 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004043 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004044 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4045 if (NonPlaceholder.isInvalid())
4046 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004047 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004048 }
4049
Richard Smith87d263e2016-12-25 08:05:23 +00004050 if (!DependentDeductionDepth &&
4051 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4052 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004053 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004054 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004055 }
4056
Richard Smith87d263e2016-12-25 08:05:23 +00004057 // Find the depth of template parameter to synthesize.
4058 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4059
Richard Smith74aeef52013-04-26 16:15:35 +00004060 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4061 // Since 'decltype(auto)' can only occur at the top of the type, we
4062 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004063 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004064 if (AT->isDecltypeAuto()) {
4065 if (isa<InitListExpr>(Init)) {
4066 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4067 return DAR_FailedAlreadyDiagnosed;
4068 }
4069
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004070 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004071 if (Deduced.isNull())
4072 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004073 // FIXME: Support a non-canonical deduced type for 'auto'.
4074 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004075 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004076 if (Result.isNull())
4077 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004078 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004079 } else if (!getLangOpts().CPlusPlus) {
4080 if (isa<InitListExpr>(Init)) {
4081 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4082 return DAR_FailedAlreadyDiagnosed;
4083 }
Richard Smith74aeef52013-04-26 16:15:35 +00004084 }
4085 }
4086
Richard Smith30482bc2011-02-20 03:19:35 +00004087 SourceLocation Loc = Init->getExprLoc();
4088
4089 LocalInstantiationScope InstScope(*this);
4090
4091 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004092 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4093 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004094 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4095 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004096 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4097 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004098
Richard Smith87d263e2016-12-25 08:05:23 +00004099 QualType FuncParam =
4100 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4101 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004102 assert(!FuncParam.isNull() &&
4103 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004104
4105 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004106 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004107 Deduced.resize(1);
4108 QualType InitType = Init->getType();
4109 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004110
Richard Smith87d263e2016-12-25 08:05:23 +00004111 TemplateDeductionInfo Info(Loc, Depth);
4112
4113 // If deduction failed, don't diagnose if the initializer is dependent; it
4114 // might acquire a matching type in the instantiation.
4115 auto DeductionFailed = [&]() -> DeduceAutoResult {
4116 if (Init->isTypeDependent()) {
4117 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4118 assert(!Result.isNull() && "substituting DependentTy can't fail");
4119 return DAR_Succeeded;
4120 }
4121 return DAR_Failed;
4122 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004123
Richard Smith74801c82012-07-08 04:13:07 +00004124 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004125 if (InitList) {
4126 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004127 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4128 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004129 Info, Deduced, TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004130 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004131 }
4132 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004133 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4134 Diag(Loc, diag::err_auto_bitfield);
4135 return DAR_FailedAlreadyDiagnosed;
4136 }
4137
James Y Knight7a22b242015-08-06 20:26:32 +00004138 if (AdjustFunctionParmAndArgTypesForDeduction(
4139 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004140 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004141
James Y Knight7a22b242015-08-06 20:26:32 +00004142 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4143 FuncParam, InitType, Info, Deduced,
4144 TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004145 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004146 }
Richard Smith30482bc2011-02-20 03:19:35 +00004147
Richard Smith87d263e2016-12-25 08:05:23 +00004148 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004149 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004150 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004151
Eli Friedmane4310952012-11-06 23:56:42 +00004152 QualType DeducedType = Deduced[0].getAsType();
4153
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004154 if (InitList) {
4155 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4156 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004157 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004158 }
4159
Richard Smith061f1e22013-04-30 21:23:01 +00004160 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004161 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004162 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004163
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004164 // Check that the deduced argument type is compatible with the original
4165 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004166 if (!InitList && !Result.isNull() &&
4167 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004168 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004169 Result)) {
4170 Result = QualType();
Richard Smith87d263e2016-12-25 08:05:23 +00004171 return DeductionFailed();
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004172 }
4173
Sebastian Redl09edce02012-01-23 22:09:39 +00004174 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004175}
4176
Simon Pilgrim728134c2016-08-12 11:43:57 +00004177QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004178 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004179 if (TypeToReplaceAuto->isDependentType())
4180 TypeToReplaceAuto = QualType();
4181 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4182 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004183}
4184
Simon Pilgrim728134c2016-08-12 11:43:57 +00004185TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004186 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004187 if (TypeToReplaceAuto->isDependentType())
4188 TypeToReplaceAuto = QualType();
4189 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4190 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004191}
4192
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004193void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4194 if (isa<InitListExpr>(Init))
4195 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004196 VDecl->isInitCapture()
4197 ? diag::err_init_capture_deduction_failure_from_init_list
4198 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004199 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4200 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004201 Diag(VDecl->getLocation(),
4202 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4203 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004204 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4205 << Init->getSourceRange();
4206}
4207
Richard Smith2a7d4812013-05-04 07:00:32 +00004208bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4209 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004210 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004211
4212 if (FD->getTemplateInstantiationPattern())
4213 InstantiateFunctionDefinition(Loc, FD);
4214
Alp Toker314cc812014-01-25 16:55:45 +00004215 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004216 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4217 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4218 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4219 }
4220
4221 return StillUndeduced;
4222}
4223
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004224static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004225MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004226 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004227 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004228 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
4230/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004231static void
4232AddImplicitObjectParameterType(ASTContext &Context,
4233 CXXMethodDecl *Method,
4234 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004235 // C++11 [temp.func.order]p3:
4236 // [...] The new parameter is of type "reference to cv A," where cv are
4237 // the cv-qualifiers of the function template (if any) and A is
4238 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004239 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004240 // The standard doesn't say explicitly, but we pick the appropriate kind of
4241 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004242 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4243 ArgTy = Context.getQualifiedType(ArgTy,
4244 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004245 if (Method->getRefQualifier() == RQ_RValue)
4246 ArgTy = Context.getRValueReferenceType(ArgTy);
4247 else
4248 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004249 ArgTypes.push_back(ArgTy);
4250}
4251
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004252/// \brief Determine whether the function template \p FT1 is at least as
4253/// specialized as \p FT2.
4254static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004255 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004256 FunctionTemplateDecl *FT1,
4257 FunctionTemplateDecl *FT2,
4258 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004259 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004260 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004262 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4263 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004265 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4266 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004267 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004268 Deduced.resize(TemplateParams->size());
4269
4270 // C++0x [temp.deduct.partial]p3:
4271 // The types used to determine the ordering depend on the context in which
4272 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004273 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004274 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004275 switch (TPOC) {
4276 case TPOC_Call: {
4277 // - In the context of a function call, the function parameter types are
4278 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004279 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4280 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004281
Eli Friedman3b5774a2012-09-19 23:27:04 +00004282 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004283 // [...] If only one of the function templates is a non-static
4284 // member, that function template is considered to have a new
4285 // first parameter inserted in its function parameter list. The
4286 // new parameter is of type "reference to cv A," where cv are
4287 // the cv-qualifiers of the function template (if any) and A is
4288 // the class of which the function template is a member.
4289 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004290 // Note that we interpret this to mean "if one of the function
4291 // templates is a non-static member and the other is a non-member";
4292 // otherwise, the ordering rules for static functions against non-static
4293 // functions don't make any sense.
4294 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004295 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4296 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004297 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004298
Richard Smithe5b52202013-09-11 00:52:39 +00004299 unsigned NumComparedArguments = NumCallArguments1;
4300
4301 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004302 // Compare 'this' from Method1 against first parameter from Method2.
4303 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4304 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004305 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004306 // Compare 'this' from Method2 against first parameter from Method1.
4307 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004308 }
4309
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004310 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004311 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004312 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004313 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregorb837ea42011-01-11 17:34:58 +00004315 // C++ [temp.func.order]p5:
4316 // The presence of unused ellipsis and default arguments has no effect on
4317 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004318 if (Args1.size() > NumComparedArguments)
4319 Args1.resize(NumComparedArguments);
4320 if (Args2.size() > NumComparedArguments)
4321 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004322 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4323 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004324 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004325 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 break;
4328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004330 case TPOC_Conversion:
4331 // - In the context of a call to a conversion operator, the return types
4332 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004333 if (DeduceTemplateArgumentsByTypeMatch(
4334 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4335 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004336 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004337 return false;
4338 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004340 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004341 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004342 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004343 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4344 FD2->getType(), FD1->getType(),
4345 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004346 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004347 return false;
4348 break;
4349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004351 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352 // In most cases, all template parameters must have values in order for
4353 // deduction to succeed, but for partial ordering purposes a template
4354 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004355 // types being used for partial ordering. [ Note: a template parameter used
4356 // in a non-deduced context is considered used. -end note]
4357 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4358 for (; ArgIdx != NumArgs; ++ArgIdx)
4359 if (Deduced[ArgIdx].isNull())
4360 break;
4361
Richard Smithcf824862016-12-30 04:32:02 +00004362 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4363 // to substitute the deduced arguments back into the template and check that
4364 // we get the right type.
4365
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004366 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004368 // as FT2.
4369 return true;
4370 }
4371
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004372 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004373 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004374 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004375 case TPOC_Call:
4376 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4377 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004378 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004379 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004380 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004382 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004383 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4384 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004385 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004387 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004388 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004389 TemplateParams->getDepth(),
4390 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004391 break;
4392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004394 for (; ArgIdx != NumArgs; ++ArgIdx)
4395 // If this argument had no value deduced but was used in one of the types
4396 // used for partial ordering, then deduction fails.
4397 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4398 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004400 return true;
4401}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregorcef1a032011-01-16 16:03:23 +00004403/// \brief Determine whether this a function template whose parameter-type-list
4404/// ends with a function parameter pack.
4405static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4406 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4407 unsigned NumParams = Function->getNumParams();
4408 if (NumParams == 0)
4409 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregorcef1a032011-01-16 16:03:23 +00004411 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4412 if (!Last->isParameterPack())
4413 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Douglas Gregorcef1a032011-01-16 16:03:23 +00004415 // Make sure that no previous parameter is a parameter pack.
4416 while (--NumParams > 0) {
4417 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4418 return false;
4419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregorcef1a032011-01-16 16:03:23 +00004421 return true;
4422}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregorbe999392009-09-15 16:23:51 +00004424/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004425/// to the rules of function template partial ordering (C++ [temp.func.order]).
4426///
4427/// \param FT1 the first function template
4428///
4429/// \param FT2 the second function template
4430///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004431/// \param TPOC the context in which we are performing partial ordering of
4432/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004433///
Richard Smithe5b52202013-09-11 00:52:39 +00004434/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4435/// only when \c TPOC is \c TPOC_Call.
4436///
4437/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4438/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004439///
Douglas Gregorbe999392009-09-15 16:23:51 +00004440/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004441/// template is more specialized, returns NULL.
4442FunctionTemplateDecl *
4443Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4444 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004445 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004446 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004447 unsigned NumCallArguments1,
4448 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004450 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004452 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004454 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004455 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004457 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004458 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004459
Douglas Gregorcef1a032011-01-16 16:03:23 +00004460 // FIXME: This mimics what GCC implements, but doesn't match up with the
4461 // proposed resolution for core issue 692. This area needs to be sorted out,
4462 // but for now we attempt to maintain compatibility.
4463 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4464 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4465 if (Variadic1 != Variadic2)
4466 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Craig Topperc3ec1492014-05-26 06:22:03 +00004468 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004469}
Douglas Gregor9b146582009-07-08 20:55:45 +00004470
Douglas Gregor450f00842009-09-25 18:43:00 +00004471/// \brief Determine if the two templates are equivalent.
4472static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4473 if (T1 == T2)
4474 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor450f00842009-09-25 18:43:00 +00004476 if (!T1 || !T2)
4477 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4480}
4481
4482/// \brief Retrieve the most specialized of the given function template
4483/// specializations.
4484///
John McCall58cc69d2010-01-27 01:50:18 +00004485/// \param SpecBegin the start iterator of the function template
4486/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004487///
John McCall58cc69d2010-01-27 01:50:18 +00004488/// \param SpecEnd the end iterator of the function template
4489/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004490///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004492/// diagnostic should occur.
4493///
4494/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4495/// no matching candidates.
4496///
4497/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4498/// occurs.
4499///
4500/// \param CandidateDiag partial diagnostic used for each function template
4501/// specialization that is a candidate in the ambiguous ordering. One parameter
4502/// in this diagnostic should be unbound, which will correspond to the string
4503/// describing the template arguments for the function template specialization.
4504///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004506/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004507UnresolvedSetIterator Sema::getMostSpecialized(
4508 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4509 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004510 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4511 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4512 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004513 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004514 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004515 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004516 FailedCandidates.NoteCandidates(*this, Loc);
4517 }
John McCall58cc69d2010-01-27 01:50:18 +00004518 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
4521 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004522 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
Douglas Gregor450f00842009-09-25 18:43:00 +00004524 // Find the function template that is better than all of the templates it
4525 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004526 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004528 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004529 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004530 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4531 FunctionTemplateDecl *Challenger
4532 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004533 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004534 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004535 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004536 Challenger)) {
4537 Best = I;
4538 BestTemplate = Challenger;
4539 }
4540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Douglas Gregor450f00842009-09-25 18:43:00 +00004542 // Make sure that the "best" function template is more specialized than all
4543 // of the others.
4544 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004545 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4546 FunctionTemplateDecl *Challenger
4547 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004548 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004550 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004551 BestTemplate)) {
4552 Ambiguous = true;
4553 break;
4554 }
4555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556
Douglas Gregor450f00842009-09-25 18:43:00 +00004557 if (!Ambiguous) {
4558 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004559 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561
Douglas Gregor450f00842009-09-25 18:43:00 +00004562 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004563 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004564 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565
Richard Smithb875c432013-05-04 01:51:08 +00004566 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004567 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4568 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004569 const auto *FD = cast<FunctionDecl>(*I);
4570 PD << FD << getTemplateArgumentBindingsText(
4571 FD->getPrimaryTemplate()->getTemplateParameters(),
4572 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004573 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004574 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004575 Diag((*I)->getLocation(), PD);
4576 }
Richard Smithb875c432013-05-04 01:51:08 +00004577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
John McCall58cc69d2010-01-27 01:50:18 +00004579 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004580}
4581
Richard Smith0da6dc42016-12-24 16:40:51 +00004582/// Determine whether one partial specialization, P1, is at least as
4583/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004584///
Richard Smith26b86ea2016-12-31 21:41:23 +00004585/// \tparam TemplateLikeDecl The kind of P2, which must be a
4586/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004587/// \param T1 The injected-class-name of P1 (faked for a variable template).
4588/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004589template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004590static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004591 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004592 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004593 // C++ [temp.class.order]p1:
4594 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595 // specialized as the second if, given the following rewrite to two
4596 // function templates, the first function template is at least as
4597 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004598 // templates (14.6.6.2):
4599 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600 // first partial specialization and has a single function parameter
4601 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004602 // arguments of the first partial specialization, and
4603 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004604 // second partial specialization and has a single function parameter
4605 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004606 // arguments of the second partial specialization.
4607 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004608 // Rather than synthesize function templates, we merely perform the
4609 // equivalent partial ordering by performing deduction directly on
4610 // the template arguments of the class template partial
4611 // specializations. This computation is slightly simpler than the
4612 // general problem of function template partial ordering, because
4613 // class template partial specializations are more constrained. We
4614 // know that every template parameter is deducible from the class
4615 // template partial specialization's template arguments, for
4616 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004617 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004618
Richard Smith0da6dc42016-12-24 16:40:51 +00004619 // Determine whether P1 is at least as specialized as P2.
4620 Deduced.resize(P2->getTemplateParameters()->size());
4621 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4622 T2, T1, Info, Deduced, TDF_None,
4623 /*PartialOrdering=*/true))
4624 return false;
4625
4626 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4627 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004628 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4629 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004630 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4631 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004632 S, P2, /*PartialOrdering=*/true,
4633 TemplateArgumentList(TemplateArgumentList::OnStack,
4634 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004635 Deduced, Info))
4636 return false;
4637
4638 return true;
4639}
4640
4641/// \brief Returns the more specialized class template partial specialization
4642/// according to the rules of partial ordering of class template partial
4643/// specializations (C++ [temp.class.order]).
4644///
4645/// \param PS1 the first class template partial specialization
4646///
4647/// \param PS2 the second class template partial specialization
4648///
4649/// \returns the more specialized class template partial specialization. If
4650/// neither partial specialization is more specialized, returns NULL.
4651ClassTemplatePartialSpecializationDecl *
4652Sema::getMoreSpecializedPartialSpecialization(
4653 ClassTemplatePartialSpecializationDecl *PS1,
4654 ClassTemplatePartialSpecializationDecl *PS2,
4655 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004656 QualType PT1 = PS1->getInjectedSpecializationType();
4657 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Richard Smith0e617ec2016-12-27 07:56:27 +00004659 TemplateDeductionInfo Info(Loc);
4660 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4661 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004662
4663 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004664 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004665
4666 return Better1 ? PS1 : PS2;
4667}
4668
Richard Smith0e617ec2016-12-27 07:56:27 +00004669bool Sema::isMoreSpecializedThanPrimary(
4670 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4671 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4672 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4673 QualType PartialT = Spec->getInjectedSpecializationType();
4674 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4675 return false;
4676 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4677 Info.clearSFINAEDiagnostic();
4678 return false;
4679 }
4680 return true;
4681}
4682
Larisse Voufo39a1e502013-08-06 01:03:05 +00004683VarTemplatePartialSpecializationDecl *
4684Sema::getMoreSpecializedPartialSpecialization(
4685 VarTemplatePartialSpecializationDecl *PS1,
4686 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004687 // Pretend the variable template specializations are class template
4688 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004689 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004690 "the partial specializations being compared should specialize"
4691 " the same template.");
4692 TemplateName Name(PS1->getSpecializedTemplate());
4693 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4694 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004695 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004696 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004697 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004698
Richard Smith0e617ec2016-12-27 07:56:27 +00004699 TemplateDeductionInfo Info(Loc);
4700 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4701 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregorbe999392009-09-15 16:23:51 +00004703 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004704 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Richard Smith0da6dc42016-12-24 16:40:51 +00004706 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004707}
4708
Richard Smith0e617ec2016-12-27 07:56:27 +00004709bool Sema::isMoreSpecializedThanPrimary(
4710 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4711 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4712 // FIXME: Cache the injected template arguments rather than recomputing
4713 // them for each partial specialization.
4714 SmallVector<TemplateArgument, 8> PrimaryArgs;
4715 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4716 PrimaryArgs);
4717
4718 TemplateName CanonTemplate =
4719 Context.getCanonicalTemplateName(TemplateName(Primary));
4720 QualType PrimaryT = Context.getTemplateSpecializationType(
4721 CanonTemplate, PrimaryArgs);
4722 QualType PartialT = Context.getTemplateSpecializationType(
4723 CanonTemplate, Spec->getTemplateArgs().asArray());
4724 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4725 return false;
4726 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4727 Info.clearSFINAEDiagnostic();
4728 return false;
4729 }
4730 return true;
4731}
4732
Richard Smith26b86ea2016-12-31 21:41:23 +00004733bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4734 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4735 // C++1z [temp.arg.template]p4: (DR 150)
4736 // A template template-parameter P is at least as specialized as a
4737 // template template-argument A if, given the following rewrite to two
4738 // function templates...
4739
4740 // Rather than synthesize function templates, we merely perform the
4741 // equivalent partial ordering by performing deduction directly on
4742 // the template parameter lists of the template template parameters.
4743 //
4744 // Given an invented class template X with the template parameter list of
4745 // A (including default arguments):
4746 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4747 TemplateParameterList *A = AArg->getTemplateParameters();
4748
4749 // - Each function template has a single function parameter whose type is
4750 // a specialization of X with template arguments corresponding to the
4751 // template parameters from the respective function template
4752 SmallVector<TemplateArgument, 8> AArgs;
4753 Context.getInjectedTemplateArgs(A, AArgs);
4754
4755 // Check P's arguments against A's parameter list. This will fill in default
4756 // template arguments as needed. AArgs are already correct by construction.
4757 // We can't just use CheckTemplateIdType because that will expand alias
4758 // templates.
4759 SmallVector<TemplateArgument, 4> PArgs;
4760 {
4761 SFINAETrap Trap(*this);
4762
4763 Context.getInjectedTemplateArgs(P, PArgs);
4764 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4765 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4766 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4767 // expansions, to form an "as written" argument list.
4768 TemplateArgument Arg = PArgs[I];
4769 if (Arg.getKind() == TemplateArgument::Pack) {
4770 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4771 Arg = *Arg.pack_begin();
4772 }
4773 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4774 Arg, QualType(), P->getParam(I)->getLocation()));
4775 }
4776 PArgs.clear();
4777
4778 // C++1z [temp.arg.template]p3:
4779 // If the rewrite produces an invalid type, then P is not at least as
4780 // specialized as A.
4781 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4782 Trap.hasErrorOccurred())
4783 return false;
4784 }
4785
4786 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4787 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4788
Richard Smith26b86ea2016-12-31 21:41:23 +00004789 // ... the function template corresponding to P is at least as specialized
4790 // as the function template corresponding to A according to the partial
4791 // ordering rules for function templates.
4792 TemplateDeductionInfo Info(Loc, A->getDepth());
4793 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4794}
4795
Mike Stump11289f42009-09-09 15:08:12 +00004796static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004797MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798 const TemplateArgument &TemplateArg,
4799 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004800 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004801 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004802
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004803/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004804/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004805static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004806MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004807 const Expr *E,
4808 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004809 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004810 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004811 // We can deduce from a pack expansion.
4812 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4813 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814
Richard Smith34349002012-07-09 03:07:20 +00004815 // Skip through any implicit casts we added while type-checking, and any
4816 // substitutions performed by template alias expansion.
4817 while (1) {
4818 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4819 E = ICE->getSubExpr();
4820 else if (const SubstNonTypeTemplateParmExpr *Subst =
4821 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4822 E = Subst->getReplacement();
4823 else
4824 break;
4825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826
4827 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004828 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004829 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004830 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004831 return;
4832
Mike Stump11289f42009-09-09 15:08:12 +00004833 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004834 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4835 if (!NTTP)
4836 return;
4837
Douglas Gregor21610382009-10-29 00:04:11 +00004838 if (NTTP->getDepth() == Depth)
4839 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004840
4841 // In C++1z mode, additional arguments may be deduced from the type of a
4842 // non-type argument.
4843 if (Ctx.getLangOpts().CPlusPlus1z)
4844 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004845}
4846
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004847/// \brief Mark the template parameters that are used by the given
4848/// nested name specifier.
4849static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004850MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004851 NestedNameSpecifier *NNS,
4852 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004853 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004854 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004855 if (!NNS)
4856 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004857
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004858 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004859 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004860 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004861 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004862}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004864/// \brief Mark the template parameters that are used by the given
4865/// template name.
4866static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004867MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004868 TemplateName Name,
4869 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004870 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004871 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004872 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4873 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004874 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4875 if (TTP->getDepth() == Depth)
4876 Used[TTP->getIndex()] = true;
4877 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004878 return;
4879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004881 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004882 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004883 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004884 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004885 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004886 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004887}
4888
4889/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004890/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004891static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004892MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004893 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004894 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004895 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004896 if (T.isNull())
4897 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor91772d12009-06-13 00:26:55 +00004899 // Non-dependent types have nothing deducible
4900 if (!T->isDependentType())
4901 return;
4902
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004903 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004904 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004905 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004906 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004907 cast<PointerType>(T)->getPointeeType(),
4908 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004909 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004910 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004911 break;
4912
4913 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004914 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004915 cast<BlockPointerType>(T)->getPointeeType(),
4916 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004917 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004918 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004919 break;
4920
4921 case Type::LValueReference:
4922 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004923 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004924 cast<ReferenceType>(T)->getPointeeType(),
4925 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004926 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004927 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004928 break;
4929
4930 case Type::MemberPointer: {
4931 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004932 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004933 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004934 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004935 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004936 break;
4937 }
4938
4939 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004940 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004941 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004942 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004943 // Fall through to check the element type
4944
4945 case Type::ConstantArray:
4946 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004947 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004948 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004949 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004950 break;
4951
4952 case Type::Vector:
4953 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004954 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004955 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004956 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004957 break;
4958
Douglas Gregor758a8692009-06-17 21:51:59 +00004959 case Type::DependentSizedExtVector: {
4960 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004961 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004962 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004963 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004964 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004965 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004966 break;
4967 }
4968
Douglas Gregor91772d12009-06-13 00:26:55 +00004969 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004970 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004971 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4972 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004973 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4974 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004975 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004976 break;
4977 }
4978
Douglas Gregor21610382009-10-29 00:04:11 +00004979 case Type::TemplateTypeParm: {
4980 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4981 if (TTP->getDepth() == Depth)
4982 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004983 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004984 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004985
Douglas Gregorfb322d82011-01-14 05:11:40 +00004986 case Type::SubstTemplateTypeParmPack: {
4987 const SubstTemplateTypeParmPackType *Subst
4988 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004989 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004990 QualType(Subst->getReplacedParameter(), 0),
4991 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004992 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004993 OnlyDeduced, Depth, Used);
4994 break;
4995 }
4996
John McCall2408e322010-04-27 00:57:59 +00004997 case Type::InjectedClassName:
4998 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4999 // fall through
5000
Douglas Gregor91772d12009-06-13 00:26:55 +00005001 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005002 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005003 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005004 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005005 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregord0ad2942010-12-23 01:24:45 +00005007 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005008 // If the template argument list of P contains a pack expansion that is
5009 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005010 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005012 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005013 break;
5014
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005015 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005016 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005017 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005018 break;
5019 }
5020
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005021 case Type::Complex:
5022 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005023 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005024 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005025 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005026 break;
5027
Eli Friedman0dfb8892011-10-06 23:00:33 +00005028 case Type::Atomic:
5029 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005030 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005031 cast<AtomicType>(T)->getValueType(),
5032 OnlyDeduced, Depth, Used);
5033 break;
5034
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005035 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005036 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005037 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005038 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005039 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040 break;
5041
John McCallc392f372010-06-11 00:33:02 +00005042 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005043 // C++14 [temp.deduct.type]p5:
5044 // The non-deduced contexts are:
5045 // -- The nested-name-specifier of a type that was specified using a
5046 // qualified-id
5047 //
5048 // C++14 [temp.deduct.type]p6:
5049 // When a type name is specified in a way that includes a non-deduced
5050 // context, all of the types that comprise that type name are also
5051 // non-deduced.
5052 if (OnlyDeduced)
5053 break;
5054
John McCallc392f372010-06-11 00:33:02 +00005055 const DependentTemplateSpecializationType *Spec
5056 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Richard Smith50d5b972015-12-30 20:56:05 +00005058 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5059 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005060
John McCallc392f372010-06-11 00:33:02 +00005061 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005062 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005063 Used);
5064 break;
5065 }
5066
John McCallbd8d9bd2010-03-01 23:49:17 +00005067 case Type::TypeOf:
5068 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005069 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005070 cast<TypeOfType>(T)->getUnderlyingType(),
5071 OnlyDeduced, Depth, Used);
5072 break;
5073
5074 case Type::TypeOfExpr:
5075 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005076 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005077 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5078 OnlyDeduced, Depth, Used);
5079 break;
5080
5081 case Type::Decltype:
5082 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005083 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005084 cast<DecltypeType>(T)->getUnderlyingExpr(),
5085 OnlyDeduced, Depth, Used);
5086 break;
5087
Alexis Hunte852b102011-05-24 22:41:36 +00005088 case Type::UnaryTransform:
5089 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005090 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005091 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005092 OnlyDeduced, Depth, Used);
5093 break;
5094
Douglas Gregord2fa7662010-12-20 02:24:11 +00005095 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005096 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005097 cast<PackExpansionType>(T)->getPattern(),
5098 OnlyDeduced, Depth, Used);
5099 break;
5100
Richard Smith30482bc2011-02-20 03:19:35 +00005101 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005102 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005103 cast<AutoType>(T)->getDeducedType(),
5104 OnlyDeduced, Depth, Used);
5105
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005106 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005107 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005108 case Type::VariableArray:
5109 case Type::FunctionNoProto:
5110 case Type::Record:
5111 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005112 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005113 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005114 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005115 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005116 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005117#define TYPE(Class, Base)
5118#define ABSTRACT_TYPE(Class, Base)
5119#define DEPENDENT_TYPE(Class, Base)
5120#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5121#include "clang/AST/TypeNodes.def"
5122 break;
5123 }
5124}
5125
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005126/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005127/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005128static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005129MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005130 const TemplateArgument &TemplateArg,
5131 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005132 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005133 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005134 switch (TemplateArg.getKind()) {
5135 case TemplateArgument::Null:
5136 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005137 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005138 break;
Mike Stump11289f42009-09-09 15:08:12 +00005139
Eli Friedmanb826a002012-09-26 02:36:12 +00005140 case TemplateArgument::NullPtr:
5141 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5142 Depth, Used);
5143 break;
5144
Douglas Gregor91772d12009-06-13 00:26:55 +00005145 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005146 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005147 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005148 break;
5149
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005150 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005151 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005152 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005154 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005155 break;
5156
5157 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005158 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005159 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005160 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161
Anders Carlssonbc343912009-06-15 17:04:53 +00005162 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005163 for (const auto &P : TemplateArg.pack_elements())
5164 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005165 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005166 }
5167}
5168
James Dennett41725122012-06-22 10:16:05 +00005169/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005170/// template argument list.
5171///
5172/// \param TemplateArgs the template argument list from which template
5173/// parameters will be deduced.
5174///
James Dennett41725122012-06-22 10:16:05 +00005175/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005176/// to indicate when the corresponding template parameter will be
5177/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005178void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005179Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005180 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005181 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005182 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183 // If the template argument list of P contains a pack expansion that is not
5184 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005185 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005187 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005188 return;
5189
Douglas Gregor91772d12009-06-13 00:26:55 +00005190 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005191 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005192 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005193}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005194
5195/// \brief Marks all of the template parameters that will be deduced by a
5196/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005197void Sema::MarkDeducedTemplateParameters(
5198 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5199 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005201 = FunctionTemplate->getTemplateParameters();
5202 Deduced.clear();
5203 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Douglas Gregorce23bae2009-09-18 23:21:38 +00005205 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5206 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005207 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005208 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005209}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005210
5211bool hasDeducibleTemplateParameters(Sema &S,
5212 FunctionTemplateDecl *FunctionTemplate,
5213 QualType T) {
5214 if (!T->isDependentType())
5215 return false;
5216
5217 TemplateParameterList *TemplateParams
5218 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005219 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005220 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005221 Deduced);
5222
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005223 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005224}