blob: c649d2ba0e23d7f887ad5987e7052438f61eacff [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"
Richard Smithc92d2062017-01-05 23:02:44 +000022#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000026#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000027#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000028
29namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000030 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000031 /// \brief Various flags that control template argument deduction.
32 ///
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
38 TDF_None = 0,
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
41 /// a reference.
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000048 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000049 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
52 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000053 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000055 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000056 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
Richard Smithcd198152017-06-07 21:46:22 +000059 /// terms of noreturn and default calling convention adjustments, or
60 /// similarly matching a declared template specialization against a
61 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
62 /// deduction where the parameter is a function type that can be converted
63 /// to the argument type.
64 TDF_AllowCompatibleFunctionType = 0x20,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000065 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000066}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000067
Douglas Gregor55ca8f62009-06-04 00:03:07 +000068using namespace clang;
69
Douglas Gregor0a29a052010-03-26 05:50:28 +000070/// \brief Compare two APSInts, extending and switching the sign as
71/// necessary to compare their values regardless of underlying type.
72static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
73 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000074 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000075 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000076 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000077
78 // If there is a signedness mismatch, correct it.
79 if (X.isSigned() != Y.isSigned()) {
80 // If the signed value is negative, then the values cannot be the same.
81 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
82 return false;
83
84 Y.setIsSigned(true);
85 X.setIsSigned(true);
86 }
87
88 return X == Y;
89}
90
Douglas Gregor181aa4a2009-06-12 18:26:56 +000091static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000092DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000093 TemplateParameterList *TemplateParams,
94 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000095 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000096 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000097 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000098
Douglas Gregor7baabef2010-12-22 18:17:10 +000099static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000100DeduceTemplateArgumentsByTypeMatch(Sema &S,
101 TemplateParameterList *TemplateParams,
102 QualType Param,
103 QualType Arg,
104 TemplateDeductionInfo &Info,
105 SmallVectorImpl<DeducedTemplateArgument> &
106 Deduced,
107 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000108 bool PartialOrdering = false,
109 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000110
111static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000112DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000113 ArrayRef<TemplateArgument> Params,
114 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000115 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000116 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
117 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000118
Richard Smith130cc442017-02-21 23:49:18 +0000119static void MarkUsedTemplateParameters(ASTContext &Ctx,
120 const TemplateArgument &TemplateArg,
121 bool OnlyDeduced, unsigned Depth,
122 llvm::SmallBitVector &Used);
123
124static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
125 bool OnlyDeduced, unsigned Level,
126 llvm::SmallBitVector &Deduced);
127
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000128/// \brief If the given expression is of a form that permits the deduction
129/// of a non-type template parameter, return the declaration of that
130/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000131static NonTypeTemplateParmDecl *
132getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000133 // If we are within an alias template, the expression may have undergone
134 // any number of parameter substitutions already.
135 while (1) {
136 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
137 E = IC->getSubExpr();
138 else if (SubstNonTypeTemplateParmExpr *Subst =
139 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
140 E = Subst->getReplacement();
141 else
142 break;
143 }
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000145 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000146 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
147 if (NTTP->getDepth() == Info.getDeducedDepth())
148 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000149
Craig Topperc3ec1492014-05-26 06:22:03 +0000150 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000151}
152
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000153/// \brief Determine whether two declaration pointers refer to the same
154/// declaration.
155static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000156 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
157 X = NX->getUnderlyingDecl();
158 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
159 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000160
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000161 return X->getCanonicalDecl() == Y->getCanonicalDecl();
162}
163
164/// \brief Verify that the given, deduced template arguments are compatible.
165///
166/// \returns The deduced template argument, or a NULL template argument if
167/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000168static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000169checkDeducedTemplateArguments(ASTContext &Context,
170 const DeducedTemplateArgument &X,
171 const DeducedTemplateArgument &Y) {
172 // We have no deduction for one or both of the arguments; they're compatible.
173 if (X.isNull())
174 return Y;
175 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000177
Richard Smith593d6a12016-12-23 01:30:39 +0000178 // If we have two non-type template argument values deduced for the same
179 // parameter, they must both match the type of the parameter, and thus must
180 // match each other's type. As we're only keeping one of them, we must check
181 // for that now. The exception is that if either was deduced from an array
182 // bound, the type is permitted to differ.
183 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
184 QualType XType = X.getNonTypeTemplateArgumentType();
185 if (!XType.isNull()) {
186 QualType YType = Y.getNonTypeTemplateArgumentType();
187 if (YType.isNull() || !Context.hasSameType(XType, YType))
188 return DeducedTemplateArgument();
189 }
190 }
191
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000192 switch (X.getKind()) {
193 case TemplateArgument::Null:
194 llvm_unreachable("Non-deduced template arguments handled above");
195
196 case TemplateArgument::Type:
197 // If two template type arguments have the same type, they're compatible.
198 if (Y.getKind() == TemplateArgument::Type &&
199 Context.hasSameType(X.getAsType(), Y.getAsType()))
200 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000201
Richard Smith5f274382016-09-28 23:55:27 +0000202 // If one of the two arguments was deduced from an array bound, the other
203 // supersedes it.
204 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
205 return X.wasDeducedFromArrayBound() ? Y : X;
206
207 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000208 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000210 case TemplateArgument::Integral:
211 // If we deduced a constant in one case and either a dependent expression or
212 // declaration in another case, keep the integral constant.
213 // If both are integral constants with the same value, keep that value.
214 if (Y.getKind() == TemplateArgument::Expression ||
215 Y.getKind() == TemplateArgument::Declaration ||
216 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000217 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000218 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000219
220 // All other combinations are incompatible.
221 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000223 case TemplateArgument::Template:
224 if (Y.getKind() == TemplateArgument::Template &&
225 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
226 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000227
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000228 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000230
231 case TemplateArgument::TemplateExpansion:
232 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000234 Y.getAsTemplateOrTemplatePattern()))
235 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000237 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000238 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000239
Richard Smith593d6a12016-12-23 01:30:39 +0000240 case TemplateArgument::Expression: {
241 if (Y.getKind() != TemplateArgument::Expression)
242 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000243
Richard Smith593d6a12016-12-23 01:30:39 +0000244 // Compare the expressions for equality
245 llvm::FoldingSetNodeID ID1, ID2;
246 X.getAsExpr()->Profile(ID1, Context, true);
247 Y.getAsExpr()->Profile(ID2, Context, true);
248 if (ID1 == ID2)
249 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000250
Richard Smith593d6a12016-12-23 01:30:39 +0000251 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000252 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000254
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000255 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000256 assert(!X.wasDeducedFromArrayBound());
257
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000258 // If we deduced a declaration and a dependent expression, keep the
259 // declaration.
260 if (Y.getKind() == TemplateArgument::Expression)
261 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000262
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000263 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000264 // integral constant and whichever type did not come from an array
265 // bound.
266 if (Y.getKind() == TemplateArgument::Integral) {
267 if (Y.wasDeducedFromArrayBound())
268 return TemplateArgument(Context, Y.getAsIntegral(),
269 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000270 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000273 // If we deduced two declarations, make sure they they refer to the
274 // same declaration.
275 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000276 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000277 return X;
278
279 // All other combinations are incompatible.
280 return DeducedTemplateArgument();
281
282 case TemplateArgument::NullPtr:
283 // If we deduced a null pointer and a dependent expression, keep the
284 // null pointer.
285 if (Y.getKind() == TemplateArgument::Expression)
286 return X;
287
288 // If we deduced a null pointer and an integral constant, keep the
289 // integral constant.
290 if (Y.getKind() == TemplateArgument::Integral)
291 return Y;
292
Richard Smith593d6a12016-12-23 01:30:39 +0000293 // If we deduced two null pointers, they are the same.
294 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000295 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000296
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 // All other combinations are incompatible.
298 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 case TemplateArgument::Pack:
301 if (Y.getKind() != TemplateArgument::Pack ||
302 X.pack_size() != Y.pack_size())
303 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
Richard Smith539e8e32017-01-04 01:48:55 +0000305 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 XAEnd = X.pack_end(),
308 YA = Y.pack_begin();
309 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000310 TemplateArgument Merged = checkDeducedTemplateArguments(
311 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
312 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
313 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000314 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000315 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317
Richard Smith539e8e32017-01-04 01:48:55 +0000318 return DeducedTemplateArgument(
319 TemplateArgument::CreatePackCopy(Context, NewPack),
320 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000322
David Blaikiee4d798f2012-01-20 21:50:17 +0000323 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000324}
325
Mike Stump11289f42009-09-09 15:08:12 +0000326/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000327/// as the given deduced template argument. All non-type template parameter
328/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000329static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000330 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000331 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
332 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000333 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000334 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
335 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000336
Richard Smith5d102892016-12-27 03:59:58 +0000337 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
338 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000339 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000340 Info.Param = NTTP;
341 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000345
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000346 Deduced[NTTP->getIndex()] = Result;
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000347 if (!S.getLangOpts().CPlusPlus17)
Richard Smithd92eddf2016-12-27 06:14:37 +0000348 return Sema::TDK_Success;
349
Richard Smith130cc442017-02-21 23:49:18 +0000350 if (NTTP->isExpandedParameterPack())
351 // FIXME: We may still need to deduce parts of the type here! But we
352 // don't have any way to find which slice of the type to use, and the
353 // type stored on the NTTP itself is nonsense. Perhaps the type of an
354 // expanded NTTP should be a pack expansion type?
355 return Sema::TDK_Success;
356
Richard Smith7bfcc052017-12-01 21:24:36 +0000357 // Get the type of the parameter for deduction. If it's a (dependent) array
358 // or function type, we will not have decayed it yet, so do that now.
359 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
Richard Smith130cc442017-02-21 23:49:18 +0000360 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
361 ParamType = Expansion->getPattern();
362
Richard Smithd92eddf2016-12-27 06:14:37 +0000363 // FIXME: It's not clear how deduction of a parameter of reference
364 // type from an argument (of non-reference type) should be performed.
365 // For now, we just remove reference types from both sides and let
366 // the final check for matching types sort out the mess.
367 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000368 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000369 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
370 /*PartialOrdering=*/false,
371 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000372}
373
Mike Stump11289f42009-09-09 15:08:12 +0000374/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000375/// from the given integral constant.
376static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
377 Sema &S, TemplateParameterList *TemplateParams,
378 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
379 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
380 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
381 return DeduceNonTypeTemplateArgument(
382 S, TemplateParams, NTTP,
383 DeducedTemplateArgument(S.Context, Value, ValueType,
384 DeducedFromArrayBound),
385 ValueType, Info, Deduced);
386}
387
388/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000389/// from the given null pointer template argument type.
390static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000391 Sema &S, TemplateParameterList *TemplateParams,
392 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000393 TemplateDeductionInfo &Info,
394 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
395 Expr *Value =
396 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
397 S.Context.NullPtrTy, NTTP->getLocation()),
398 NullPtrType, CK_NullToPointer)
399 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000400 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
401 DeducedTemplateArgument(Value),
402 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000403}
404
405/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000406/// from the given type- or value-dependent expression.
407///
408/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000409static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
410 Sema &S, TemplateParameterList *TemplateParams,
411 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
412 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000413 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
414 DeducedTemplateArgument(Value),
415 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000416}
417
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000418/// \brief Deduce the value of the given non-type template parameter
419/// from the given declaration.
420///
421/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000422static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
423 Sema &S, TemplateParameterList *TemplateParams,
424 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
425 TemplateDeductionInfo &Info,
426 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000427 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000428 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000429 return DeduceNonTypeTemplateArgument(
430 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000431}
432
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000433static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000434DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000436 TemplateName Param,
437 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000438 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000439 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000440 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000441 if (!ParamDecl) {
442 // The parameter type is dependent and is not a template template parameter,
443 // so there is nothing that we can deduce.
444 return Sema::TDK_Success;
445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000446
Douglas Gregoradee3e32009-11-11 23:06:43 +0000447 if (TemplateTemplateParmDecl *TempParam
448 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000449 // If we're not deducing at this depth, there's nothing to deduce.
450 if (TempParam->getDepth() != Info.getDeducedDepth())
451 return Sema::TDK_Success;
452
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000453 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000455 Deduced[TempParam->getIndex()],
456 NewDeduced);
457 if (Result.isNull()) {
458 Info.Param = TempParam;
459 Info.FirstArg = Deduced[TempParam->getIndex()];
460 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000464 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467
Douglas Gregoradee3e32009-11-11 23:06:43 +0000468 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000469 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000470 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471
Douglas Gregoradee3e32009-11-11 23:06:43 +0000472 // Mismatch of non-dependent template parameter to argument.
473 Info.FirstArg = TemplateArgument(Param);
474 Info.SecondArg = TemplateArgument(Arg);
475 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000476}
477
Mike Stump11289f42009-09-09 15:08:12 +0000478/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000479/// type (which is a template-id) with the template argument type.
480///
Chandler Carruthc1263112010-02-07 21:33:28 +0000481/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000482///
483/// \param TemplateParams the template parameters that we are deducing
484///
485/// \param Param the parameter type
486///
487/// \param Arg the argument type
488///
489/// \param Info information about the template argument deduction itself
490///
491/// \param Deduced the deduced template arguments
492///
493/// \returns the result of template argument deduction so far. Note that a
494/// "success" result means that template argument deduction has not yet failed,
495/// but it may still fail, later, for other reasons.
496static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000497DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 TemplateParameterList *TemplateParams,
499 const TemplateSpecializationType *Param,
500 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000501 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000502 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000503 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregore81f3e72009-07-07 23:09:34 +0000505 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000506 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 = dyn_cast<TemplateSpecializationType>(Arg)) {
508 // Perform template argument deduction for the template name.
509 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000510 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000511 Param->getTemplateName(),
512 SpecArg->getTemplateName(),
513 Info, Deduced))
514 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregore81f3e72009-07-07 23:09:34 +0000517 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000518 // argument. Ignore any missing/extra arguments, since they could be
519 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000520 return DeduceTemplateArguments(S, TemplateParams,
521 Param->template_arguments(),
522 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000523 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregore81f3e72009-07-07 23:09:34 +0000526 // If the argument type is a class template specialization, we
527 // perform template argument deduction using its template
528 // arguments.
529 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000530 if (!RecordArg) {
531 Info.FirstArg = TemplateArgument(QualType(Param, 0));
532 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000533 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000534 }
Mike Stump11289f42009-09-09 15:08:12 +0000535
536 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000537 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000538 if (!SpecArg) {
539 Info.FirstArg = TemplateArgument(QualType(Param, 0));
540 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000541 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Douglas Gregore81f3e72009-07-07 23:09:34 +0000544 // Perform template argument deduction for the template name.
545 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000546 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000547 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000548 Param->getTemplateName(),
549 TemplateName(SpecArg->getSpecializedTemplate()),
550 Info, Deduced))
551 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregor7baabef2010-12-22 18:17:10 +0000553 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000554 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
555 SpecArg->getTemplateArgs().asArray(), Info,
556 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000557}
558
John McCall08569062010-08-28 22:14:41 +0000559/// \brief Determines whether the given type is an opaque type that
560/// might be more qualified when instantiated.
561static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
562 switch (T->getTypeClass()) {
563 case Type::TypeOfExpr:
564 case Type::TypeOf:
565 case Type::DependentName:
566 case Type::Decltype:
567 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000568 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000569 return true;
570
571 case Type::ConstantArray:
572 case Type::IncompleteArray:
573 case Type::VariableArray:
574 case Type::DependentSizedArray:
575 return IsPossiblyOpaquelyQualifiedType(
576 cast<ArrayType>(T)->getElementType());
577
578 default:
579 return false;
580 }
581}
582
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000583/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000585getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000586 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
587 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Douglas Gregor5499af42011-01-05 23:12:31 +0000589 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
590 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor5499af42011-01-05 23:12:31 +0000592 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
593 return std::make_pair(TTP->getDepth(), TTP->getIndex());
594}
595
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000596/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000598getDepthAndIndex(UnexpandedParameterPack UPP) {
599 if (const TemplateTypeParmType *TTP
600 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
601 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000603 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
604}
605
Douglas Gregor5499af42011-01-05 23:12:31 +0000606/// \brief Helper function to build a TemplateParameter when we don't
607/// know its type statically.
608static TemplateParameter makeTemplateParameter(Decl *D) {
609 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
610 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000611 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000612 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613
Douglas Gregor5499af42011-01-05 23:12:31 +0000614 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
615}
616
Richard Smith0a80d572014-05-29 01:12:14 +0000617/// A pack that we're currently deducing.
618struct clang::DeducedPack {
619 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000620
Richard Smith0a80d572014-05-29 01:12:14 +0000621 // The index of the pack.
622 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Richard Smith0a80d572014-05-29 01:12:14 +0000624 // The old value of the pack before we started deducing it.
625 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000626
Richard Smith0a80d572014-05-29 01:12:14 +0000627 // A deferred value of this pack from an inner deduction, that couldn't be
628 // deduced because this deduction hadn't happened yet.
629 DeducedTemplateArgument DeferredDeduction;
630
631 // The new value of the pack.
632 SmallVector<DeducedTemplateArgument, 4> New;
633
634 // The outer deduction for this pack, if any.
635 DeducedPack *Outer;
636};
637
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000638namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000639/// A scope in which we're performing pack deduction.
640class PackDeductionScope {
641public:
642 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
643 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
644 TemplateDeductionInfo &Info, TemplateArgument Pattern)
645 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith130cc442017-02-21 23:49:18 +0000646 // Dig out the partially-substituted pack, if there is one.
647 const TemplateArgument *PartialPackArgs = nullptr;
648 unsigned NumPartialPackArgs = 0;
649 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
650 if (auto *Scope = S.CurrentInstantiationScope)
651 if (auto *Partial = Scope->getPartiallySubstitutedPack(
652 &PartialPackArgs, &NumPartialPackArgs))
653 PartialPackDepthIndex = getDepthAndIndex(Partial);
654
Richard Smith0a80d572014-05-29 01:12:14 +0000655 // Compute the set of template parameter indices that correspond to
656 // parameter packs expanded by the pack expansion.
657 {
658 llvm::SmallBitVector SawIndices(TemplateParams->size());
Richard Smith130cc442017-02-21 23:49:18 +0000659
660 auto AddPack = [&](unsigned Index) {
661 if (SawIndices[Index])
662 return;
663 SawIndices[Index] = true;
664
665 // Save the deduced template argument for the parameter pack expanded
666 // by this pack expansion, then clear out the deduction.
667 DeducedPack Pack(Index);
668 Pack.Saved = Deduced[Index];
669 Deduced[Index] = TemplateArgument();
670
671 Packs.push_back(Pack);
672 };
673
674 // First look for unexpanded packs in the pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000675 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
676 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
677 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
678 unsigned Depth, Index;
679 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith130cc442017-02-21 23:49:18 +0000680 if (Depth == Info.getDeducedDepth())
681 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000682 }
Richard Smith130cc442017-02-21 23:49:18 +0000683 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
684
685 // This pack expansion will have been partially expanded iff the only
686 // unexpanded parameter pack within it is the partially-substituted pack.
687 IsPartiallyExpanded =
688 Packs.size() == 1 &&
689 PartialPackDepthIndex ==
690 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
691
692 // Skip over the pack elements that were expanded into separate arguments.
693 if (IsPartiallyExpanded)
694 PackElements += NumPartialPackArgs;
695
696 // We can also have deduced template parameters that do not actually
697 // appear in the pattern, but can be deduced by it (the type of a non-type
698 // template parameter pack, in particular). These won't have prevented us
699 // from partially expanding the pack.
700 llvm::SmallBitVector Used(TemplateParams->size());
701 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
702 Info.getDeducedDepth(), Used);
703 for (int Index = Used.find_first(); Index != -1;
704 Index = Used.find_next(Index))
705 if (TemplateParams->getParam(Index)->isParameterPack())
706 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000707 }
Richard Smith0a80d572014-05-29 01:12:14 +0000708
709 for (auto &Pack : Packs) {
710 if (Info.PendingDeducedPacks.size() > Pack.Index)
711 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
712 else
713 Info.PendingDeducedPacks.resize(Pack.Index + 1);
714 Info.PendingDeducedPacks[Pack.Index] = &Pack;
715
Richard Smith130cc442017-02-21 23:49:18 +0000716 if (PartialPackDepthIndex ==
717 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
718 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
719 // We pre-populate the deduced value of the partially-substituted
720 // pack with the specified value. This is not entirely correct: the
721 // value is supposed to have been substituted, not deduced, but the
722 // cases where this is observable require an exact type match anyway.
723 //
724 // FIXME: If we could represent a "depth i, index j, pack elem k"
725 // parameter, we could substitute the partially-substituted pack
726 // everywhere and avoid this.
727 if (Pack.New.size() > PackElements)
728 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000729 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000730 }
731 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000732
Richard Smith0a80d572014-05-29 01:12:14 +0000733 ~PackDeductionScope() {
734 for (auto &Pack : Packs)
735 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737
Richard Smithde0d34a2017-01-09 07:14:40 +0000738 /// Determine whether this pack has already been partially expanded into a
739 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000740 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000741
Richard Smith0a80d572014-05-29 01:12:14 +0000742 /// Move to deducing the next element in each pack that is being deduced.
743 void nextPackElement() {
744 // Capture the deduced template arguments for each parameter pack expanded
745 // by this pack expansion, add them to the list of arguments we've deduced
746 // for that pack, then clear out the deduced argument.
747 for (auto &Pack : Packs) {
748 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000749 if (!Pack.New.empty() || !DeducedArg.isNull()) {
750 while (Pack.New.size() < PackElements)
751 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000752 if (Pack.New.size() == PackElements)
753 Pack.New.push_back(DeducedArg);
754 else
755 Pack.New[PackElements] = DeducedArg;
756 DeducedArg = Pack.New.size() > PackElements + 1
757 ? Pack.New[PackElements + 1]
758 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000759 }
760 }
Richard Smith539e8e32017-01-04 01:48:55 +0000761 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000762 }
763
764 /// \brief Finish template argument deduction for a set of argument packs,
765 /// producing the argument packs and checking for consistency with prior
766 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000767 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000768 // Build argument packs for each of the parameter packs expanded by this
769 // pack expansion.
770 for (auto &Pack : Packs) {
771 // Put back the old value for this pack.
772 Deduced[Pack.Index] = Pack.Saved;
773
774 // Build or find a new value for this pack.
775 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000776 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000777 if (Pack.DeferredDeduction.isNull()) {
778 // We were not able to deduce anything for this parameter pack
779 // (because it only appeared in non-deduced contexts), so just
780 // restore the saved argument pack.
781 continue;
782 }
783
784 NewPack = Pack.DeferredDeduction;
785 Pack.DeferredDeduction = TemplateArgument();
786 } else if (Pack.New.empty()) {
787 // If we deduced an empty argument pack, create it now.
788 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
789 } else {
790 TemplateArgument *ArgumentPack =
791 new (S.Context) TemplateArgument[Pack.New.size()];
792 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
793 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000794 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000795 // FIXME: This is wrong, it's possible that some pack elements are
796 // deduced from an array bound and others are not:
797 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
798 // g({1, 2, 3}, {{}, {}});
799 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000800 Pack.New[0].wasDeducedFromArrayBound());
801 }
802
803 // Pick where we're going to put the merged pack.
804 DeducedTemplateArgument *Loc;
805 if (Pack.Outer) {
806 if (Pack.Outer->DeferredDeduction.isNull()) {
807 // Defer checking this pack until we have a complete pack to compare
808 // it against.
809 Pack.Outer->DeferredDeduction = NewPack;
810 continue;
811 }
812 Loc = &Pack.Outer->DeferredDeduction;
813 } else {
814 Loc = &Deduced[Pack.Index];
815 }
816
817 // Check the new pack matches any previous value.
818 DeducedTemplateArgument OldPack = *Loc;
819 DeducedTemplateArgument Result =
820 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
821
822 // If we deferred a deduction of this pack, check that one now too.
823 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
824 OldPack = Result;
825 NewPack = Pack.DeferredDeduction;
826 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
827 }
828
829 if (Result.isNull()) {
830 Info.Param =
831 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
832 Info.FirstArg = OldPack;
833 Info.SecondArg = NewPack;
834 return Sema::TDK_Inconsistent;
835 }
836
837 *Loc = Result;
838 }
839
840 return Sema::TDK_Success;
841 }
842
843private:
844 Sema &S;
845 TemplateParameterList *TemplateParams;
846 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
847 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000848 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000849 bool IsPartiallyExpanded = false;
Richard Smith0a80d572014-05-29 01:12:14 +0000850
851 SmallVector<DeducedPack, 2> Packs;
852};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000853} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000854
Douglas Gregor5499af42011-01-05 23:12:31 +0000855/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856/// types to the list of argument types, as in the parameter-type-lists of
857/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000858///
859/// \param S The semantic analysis object within which we are deducing
860///
861/// \param TemplateParams The template parameters that we are deducing
862///
863/// \param Params The list of parameter types
864///
865/// \param NumParams The number of types in \c Params
866///
867/// \param Args The list of argument types
868///
869/// \param NumArgs The number of types in \c Args
870///
871/// \param Info information about the template argument deduction itself
872///
873/// \param Deduced the deduced template arguments
874///
875/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
876/// how template argument deduction is performed.
877///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000878/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000880/// (C++0x [temp.deduct.partial]).
881///
Douglas Gregor5499af42011-01-05 23:12:31 +0000882/// \returns the result of template argument deduction so far. Note that a
883/// "success" result means that template argument deduction has not yet failed,
884/// but it may still fail, later, for other reasons.
885static Sema::TemplateDeductionResult
886DeduceTemplateArguments(Sema &S,
887 TemplateParameterList *TemplateParams,
888 const QualType *Params, unsigned NumParams,
889 const QualType *Args, unsigned NumArgs,
890 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000891 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000892 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000893 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000894 // Fast-path check to see if we have too many/too few arguments.
895 if (NumParams != NumArgs &&
896 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
897 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000898 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
Douglas Gregor5499af42011-01-05 23:12:31 +0000900 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901 // Similarly, if P has a form that contains (T), then each parameter type
902 // Pi of the respective parameter-type- list of P is compared with the
903 // corresponding parameter type Ai of the corresponding parameter-type-list
904 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000905 unsigned ArgIdx = 0, ParamIdx = 0;
906 for (; ParamIdx != NumParams; ++ParamIdx) {
907 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000909 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
910 if (!Expansion) {
911 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912
Douglas Gregor5499af42011-01-05 23:12:31 +0000913 // Make sure we have an argument.
914 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000915 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000917 if (isa<PackExpansionType>(Args[ArgIdx])) {
918 // C++0x [temp.deduct.type]p22:
919 // If the original function parameter associated with A is a function
920 // parameter pack and the function parameter associated with P is not
921 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000922 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924
Douglas Gregor5499af42011-01-05 23:12:31 +0000925 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000926 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
927 Params[ParamIdx], Args[ArgIdx],
928 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000929 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000930 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000931
Douglas Gregor5499af42011-01-05 23:12:31 +0000932 ++ArgIdx;
933 continue;
934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000936 // C++0x [temp.deduct.type]p5:
937 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000939 // parameter-declaration-clause.
940 if (ParamIdx + 1 < NumParams)
941 return Sema::TDK_Success;
942
Douglas Gregor5499af42011-01-05 23:12:31 +0000943 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000945 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000947 // comparison deduces template arguments for subsequent positions in the
948 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
Douglas Gregor5499af42011-01-05 23:12:31 +0000950 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000951 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952
Douglas Gregor5499af42011-01-05 23:12:31 +0000953 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000954 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000956 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
957 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000958 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000959 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Richard Smith0a80d572014-05-29 01:12:14 +0000961 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963
Douglas Gregor5499af42011-01-05 23:12:31 +0000964 // Build argument packs for each of the parameter packs expanded by this
965 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000966 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregor5499af42011-01-05 23:12:31 +0000970 // Make sure we don't have any extra arguments.
971 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000972 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973
Douglas Gregor5499af42011-01-05 23:12:31 +0000974 return Sema::TDK_Success;
975}
976
Douglas Gregor1d684c22011-04-28 00:56:09 +0000977/// \brief Determine whether the parameter has qualifiers that are either
978/// inconsistent with or a superset of the argument's qualifiers.
979static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
980 QualType ArgType) {
981 Qualifiers ParamQs = ParamType.getQualifiers();
982 Qualifiers ArgQs = ArgType.getQualifiers();
983
984 if (ParamQs == ArgQs)
985 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000986
Douglas Gregor1d684c22011-04-28 00:56:09 +0000987 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000988 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000989 ParamQs.hasObjCGCAttr())
990 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000991
Douglas Gregor1d684c22011-04-28 00:56:09 +0000992 // Mismatched (but not missing) address spaces.
993 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
994 ParamQs.hasAddressSpace())
995 return true;
996
John McCall31168b02011-06-15 23:02:42 +0000997 // Mismatched (but not missing) Objective-C lifetime qualifiers.
998 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
999 ParamQs.hasObjCLifetime())
1000 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001001
Douglas Gregor1d684c22011-04-28 00:56:09 +00001002 // CVR qualifier superset.
1003 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
1004 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
1005 == ParamQs.getCVRQualifiers());
1006}
1007
Douglas Gregor19a41f12013-04-17 08:45:07 +00001008/// \brief Compare types for equality with respect to possibly compatible
1009/// function types (noreturn adjustment, implicit calling conventions). If any
1010/// of parameter and argument is not a function, just perform type comparison.
1011///
1012/// \param Param the template parameter type.
1013///
1014/// \param Arg the argument type.
1015bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1016 CanQualType Arg) {
1017 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1018 *ArgFunction = Arg->getAs<FunctionType>();
1019
1020 // Just compare if not functions.
1021 if (!ParamFunction || !ArgFunction)
1022 return Param == Arg;
1023
Richard Smith3c4f8d22016-10-16 17:54:23 +00001024 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001025 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001026 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001027 return Arg == Context.getCanonicalType(AdjustedParam);
1028
1029 // FIXME: Compatible calling conventions.
1030
1031 return Param == Arg;
1032}
1033
Richard Smith32918772017-02-14 00:25:28 +00001034/// Get the index of the first template parameter that was originally from the
1035/// innermost template-parameter-list. This is 0 except when we concatenate
1036/// the template parameter lists of a class template and a constructor template
1037/// when forming an implicit deduction guide.
1038static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001039 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1040 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001041 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001042 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001043}
1044
1045/// Determine whether a type denotes a forwarding reference.
1046static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1047 // C++1z [temp.deduct.call]p3:
1048 // A forwarding reference is an rvalue reference to a cv-unqualified
1049 // template parameter that does not represent a template parameter of a
1050 // class template.
1051 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1052 if (ParamRef->getPointeeType().getQualifiers())
1053 return false;
1054 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1055 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1056 }
1057 return false;
1058}
1059
Douglas Gregorcceb9752009-06-26 18:27:22 +00001060/// \brief Deduce the template arguments by comparing the parameter type and
1061/// the argument type (C++ [temp.deduct.type]).
1062///
Chandler Carruthc1263112010-02-07 21:33:28 +00001063/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001064///
1065/// \param TemplateParams the template parameters that we are deducing
1066///
1067/// \param ParamIn the parameter type
1068///
1069/// \param ArgIn the argument type
1070///
1071/// \param Info information about the template argument deduction itself
1072///
1073/// \param Deduced the deduced template arguments
1074///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001075/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001076/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001077///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001078/// \param PartialOrdering Whether we're performing template argument deduction
1079/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1080///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001081/// \returns the result of template argument deduction so far. Note that a
1082/// "success" result means that template argument deduction has not yet failed,
1083/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001084static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001085DeduceTemplateArgumentsByTypeMatch(Sema &S,
1086 TemplateParameterList *TemplateParams,
1087 QualType ParamIn, QualType ArgIn,
1088 TemplateDeductionInfo &Info,
1089 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1090 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001091 bool PartialOrdering,
1092 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001093 // We only want to look at the canonical types, since typedefs and
1094 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001095 QualType Param = S.Context.getCanonicalType(ParamIn);
1096 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001097
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001098 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001100 if (const PackExpansionType *ArgExpansion
1101 = dyn_cast<PackExpansionType>(Arg))
1102 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
Douglas Gregorb837ea42011-01-11 17:34:58 +00001104 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001105 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106 // Before the partial ordering is done, certain transformations are
1107 // performed on the types used for partial ordering:
1108 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001109 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1110 if (ParamRef)
1111 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Douglas Gregorb837ea42011-01-11 17:34:58 +00001113 // - If A is a reference type, A is replaced by the type referred to.
1114 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1115 if (ArgRef)
1116 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001117
Richard Smithed563c22015-02-20 04:45:22 +00001118 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1119 // C++11 [temp.deduct.partial]p9:
1120 // If, for a given type, deduction succeeds in both directions (i.e.,
1121 // the types are identical after the transformations above) and both
1122 // P and A were reference types [...]:
1123 // - if [one type] was an lvalue reference and [the other type] was
1124 // not, [the other type] is not considered to be at least as
1125 // specialized as [the first type]
1126 // - if [one type] is more cv-qualified than [the other type],
1127 // [the other type] is not considered to be at least as specialized
1128 // as [the first type]
1129 // Objective-C ARC adds:
1130 // - [one type] has non-trivial lifetime, [the other type] has
1131 // __unsafe_unretained lifetime, and the types are otherwise
1132 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001133 //
Richard Smithed563c22015-02-20 04:45:22 +00001134 // A is "considered to be at least as specialized" as P iff deduction
1135 // succeeds, so we model this as a deduction failure. Note that
1136 // [the first type] is P and [the other type] is A here; the standard
1137 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001138 Qualifiers ParamQuals = Param.getQualifiers();
1139 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001140 if ((ParamRef->isLValueReferenceType() &&
1141 !ArgRef->isLValueReferenceType()) ||
1142 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1143 (ParamQuals.hasNonTrivialObjCLifetime() &&
1144 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1145 ParamQuals.withoutObjCLifetime() ==
1146 ArgQuals.withoutObjCLifetime())) {
1147 Info.FirstArg = TemplateArgument(ParamIn);
1148 Info.SecondArg = TemplateArgument(ArgIn);
1149 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001150 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001152
Richard Smithed563c22015-02-20 04:45:22 +00001153 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001154 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001155 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001156 // version of P.
1157 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001158 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001159 // version of A.
1160 Arg = Arg.getUnqualifiedType();
1161 } else {
1162 // C++0x [temp.deduct.call]p4 bullet 1:
1163 // - If the original P is a reference type, the deduced A (i.e., the type
1164 // referred to by the reference) can be more cv-qualified than the
1165 // transformed A.
1166 if (TDF & TDF_ParamWithReferenceType) {
1167 Qualifiers Quals;
1168 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1169 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001170 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001171 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173
Douglas Gregor85f240c2011-01-25 17:19:08 +00001174 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1175 // C++0x [temp.deduct.type]p10:
1176 // If P and A are function types that originated from deduction when
1177 // taking the address of a function template (14.8.2.2) or when deducing
1178 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001180 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1181 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001183 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1184 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001185 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001186 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001187 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1188 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001189 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001192 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001193 // A template type argument T, a template template argument TT or a
1194 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001195 // the following forms:
1196 //
1197 // T
1198 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001199 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001200 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001201 // Just skip any attempts to deduce from a placeholder type or a parameter
1202 // at a different depth.
1203 if (Arg->isPlaceholderType() ||
1204 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001205 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001206
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001207 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001208 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor60454822009-07-22 20:02:25 +00001210 // If the argument type is an array type, move the qualifiers up to the
1211 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001212 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001213 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001214 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001215 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001216 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001217 RecanonicalizeArg = true;
1218 }
1219 }
Mike Stump11289f42009-09-09 15:08:12 +00001220
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001221 // The argument type can not be less qualified than the parameter
1222 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001223 if (!(TDF & TDF_IgnoreQualifiers) &&
1224 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001225 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001226 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001227 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001228 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001229 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001230
Richard Smith87d263e2016-12-25 08:05:23 +00001231 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1232 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001233 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001234 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001235
Douglas Gregor1d684c22011-04-28 00:56:09 +00001236 // Remove any qualifiers on the parameter from the deduced type.
1237 // We checked the qualifiers for consistency above.
1238 Qualifiers DeducedQs = DeducedType.getQualifiers();
1239 Qualifiers ParamQs = Param.getQualifiers();
1240 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1241 if (ParamQs.hasObjCGCAttr())
1242 DeducedQs.removeObjCGCAttr();
1243 if (ParamQs.hasAddressSpace())
1244 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001245 if (ParamQs.hasObjCLifetime())
1246 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001247
Douglas Gregore46db902011-06-17 22:11:49 +00001248 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001249 // If template deduction would produce a lifetime qualifier on a type
1250 // that is not a lifetime type, template argument deduction fails.
1251 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1252 !DeducedType->isDependentType()) {
1253 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1254 Info.FirstArg = TemplateArgument(Param);
1255 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001256 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001257 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001258
Douglas Gregora4f2b432011-07-26 14:53:44 +00001259 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001260 // If template deduction would produce an argument type with lifetime type
1261 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001262 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001263 DeducedType->isObjCLifetimeType() &&
1264 !DeducedQs.hasObjCLifetime())
1265 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001266
Douglas Gregor1d684c22011-04-28 00:56:09 +00001267 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1268 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001269
Douglas Gregord6605db2009-07-22 21:30:48 +00001270 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001271 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Richard Smith5f274382016-09-28 23:55:27 +00001273 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001275 Deduced[Index],
1276 NewDeduced);
1277 if (Result.isNull()) {
1278 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1279 Info.FirstArg = Deduced[Index];
1280 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001284 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001286 }
1287
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001288 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001289 Info.FirstArg = TemplateArgument(ParamIn);
1290 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001291
Douglas Gregorfb322d82011-01-14 05:11:40 +00001292 // If the parameter is an already-substituted template parameter
1293 // pack, do nothing: we don't know which of its arguments to look
1294 // at, so we have to wait until all of the parameter packs in this
1295 // expansion have arguments.
1296 if (isa<SubstTemplateTypeParmPackType>(Param))
1297 return Sema::TDK_Success;
1298
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001299 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001300 CanQualType CanParam = S.Context.getCanonicalType(Param);
1301 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001302 if (!(TDF & TDF_IgnoreQualifiers)) {
1303 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001304 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001305 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001306 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001307 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001308 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001309 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001310
Douglas Gregor194ea692012-03-11 03:29:50 +00001311 // If the parameter type is not dependent, there is nothing to deduce.
1312 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001313 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001314 bool NonDeduced =
1315 (TDF & TDF_AllowCompatibleFunctionType)
1316 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1317 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001318 if (NonDeduced) {
1319 return Sema::TDK_NonDeducedMismatch;
1320 }
1321 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001322 return Sema::TDK_Success;
1323 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001324 } else if (!Param->isDependentType()) {
1325 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1326 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001327 bool Success =
1328 (TDF & TDF_AllowCompatibleFunctionType)
1329 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1330 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001331 if (Success)
1332 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001333 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001334
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001335 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001336 // Non-canonical types cannot appear here.
1337#define NON_CANONICAL_TYPE(Class, Base) \
1338 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1339#define TYPE(Class, Base)
1340#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001341
Douglas Gregor39c02722011-06-15 16:02:29 +00001342 case Type::TemplateTypeParm:
1343 case Type::SubstTemplateTypeParmPack:
1344 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001345
1346 // These types cannot be dependent, so simply check whether the types are
1347 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001348 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001349 case Type::VariableArray:
1350 case Type::Vector:
1351 case Type::FunctionNoProto:
1352 case Type::Record:
1353 case Type::Enum:
1354 case Type::ObjCObject:
1355 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001356 case Type::ObjCObjectPointer: {
1357 if (TDF & TDF_SkipNonDependent)
1358 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001359
Douglas Gregor194ea692012-03-11 03:29:50 +00001360 if (TDF & TDF_IgnoreQualifiers) {
1361 Param = Param.getUnqualifiedType();
1362 Arg = Arg.getUnqualifiedType();
1363 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001364
Douglas Gregor194ea692012-03-11 03:29:50 +00001365 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1366 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001367
1368 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001369 case Type::Complex:
1370 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001371 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1372 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001373 ComplexArg->getElementType(),
1374 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001375
1376 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001377
1378 // _Atomic T [extension]
1379 case Type::Atomic:
1380 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001381 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001382 cast<AtomicType>(Param)->getValueType(),
1383 AtomicArg->getValueType(),
1384 Info, Deduced, TDF);
1385
1386 return Sema::TDK_NonDeducedMismatch;
1387
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001388 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001389 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001390 QualType PointeeType;
1391 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1392 PointeeType = PointerArg->getPointeeType();
1393 } else if (const ObjCObjectPointerType *PointerArg
1394 = Arg->getAs<ObjCObjectPointerType>()) {
1395 PointeeType = PointerArg->getPointeeType();
1396 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001397 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001398 }
Mike Stump11289f42009-09-09 15:08:12 +00001399
Douglas Gregorfc516c92009-06-26 23:27:24 +00001400 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001401 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1402 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001403 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001404 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001407 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001408 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001409 const LValueReferenceType *ReferenceArg =
1410 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001411 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001412 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001413
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001414 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001415 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001416 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001417 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001418
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001419 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001420 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001421 const RValueReferenceType *ReferenceArg =
1422 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001423 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001424 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001425
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001426 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1427 cast<RValueReferenceType>(Param)->getPointeeType(),
1428 ReferenceArg->getPointeeType(),
1429 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001430 }
Mike Stump11289f42009-09-09 15:08:12 +00001431
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001432 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001433 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001434 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001435 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001436 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001437 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001438
John McCallf7332682010-08-19 00:20:19 +00001439 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001440 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1441 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1442 IncompleteArrayArg->getElementType(),
1443 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001444 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001445
1446 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001447 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001448 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001449 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001450 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001451 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001452
1453 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001454 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001455 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001456 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001457
John McCallf7332682010-08-19 00:20:19 +00001458 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001459 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1460 ConstantArrayParm->getElementType(),
1461 ConstantArrayArg->getElementType(),
1462 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001463 }
1464
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001465 // type [i]
1466 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001467 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001468 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001469 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001470
John McCallf7332682010-08-19 00:20:19 +00001471 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1472
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001473 // Check the element type of the arrays
1474 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001475 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001476 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001477 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1478 DependentArrayParm->getElementType(),
1479 ArrayArg->getElementType(),
1480 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001481 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001483 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001484 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001485 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001486 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001487 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001488
1489 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001490 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001491 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1492 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001493 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001494 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1495 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001496 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001497 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001498 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001499 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001500 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001501 if (const DependentSizedArrayType *DependentArrayArg
1502 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001503 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001504 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001505 DependentArrayArg->getSizeExpr(),
1506 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001508 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001509 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
1512 // type(*)(T)
1513 // T(*)()
1514 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001515 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001516 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001517 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001518 dyn_cast<FunctionProtoType>(Arg);
1519 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001520 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001521
1522 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001523 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001524
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001525 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001526 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001528 != FunctionProtoArg->getRefQualifier() ||
1529 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001530 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001531
Anders Carlsson2128ec72009-06-08 15:19:08 +00001532 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001533 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1534 S, TemplateParams, FunctionProtoParam->getReturnType(),
1535 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001536 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001537
Richard Smithcd198152017-06-07 21:46:22 +00001538 // Check parameter types.
1539 if (auto Result = DeduceTemplateArguments(
1540 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1541 FunctionProtoParam->getNumParams(),
1542 FunctionProtoArg->param_type_begin(),
1543 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1544 return Result;
1545
1546 if (TDF & TDF_AllowCompatibleFunctionType)
1547 return Sema::TDK_Success;
1548
1549 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1550 // deducing through the noexcept-specifier if it's part of the canonical
1551 // type. libstdc++ relies on this.
1552 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1553 if (NonTypeTemplateParmDecl *NTTP =
1554 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1555 : nullptr) {
1556 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1557 "saw non-type template parameter with wrong depth");
1558
1559 llvm::APSInt Noexcept(1);
1560 switch (FunctionProtoArg->canThrow(S.Context)) {
1561 case CT_Cannot:
1562 Noexcept = 1;
1563 LLVM_FALLTHROUGH;
1564
1565 case CT_Can:
1566 // We give E in noexcept(E) the "deduced from array bound" treatment.
1567 // FIXME: Should we?
1568 return DeduceNonTypeTemplateArgument(
1569 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1570 /*ArrayBound*/true, Info, Deduced);
1571
1572 case CT_Dependent:
1573 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1574 return DeduceNonTypeTemplateArgument(
1575 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1576 // Can't deduce anything from throw(T...).
1577 break;
1578 }
1579 }
1580 // FIXME: Detect non-deduced exception specification mismatches?
1581
1582 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
John McCalle78aac42010-03-10 03:28:59 +00001585 case Type::InjectedClassName: {
1586 // Treat a template's injected-class-name as if the template
1587 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001588 Param = cast<InjectedClassNameType>(Param)
1589 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001590 assert(isa<TemplateSpecializationType>(Param) &&
1591 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001592 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001593 }
1594
Douglas Gregor705c9002009-06-26 20:57:09 +00001595 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001596 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001597 // TT<T>
1598 // TT<i>
1599 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001600 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001601 const TemplateSpecializationType *SpecParam =
1602 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001603
Richard Smith9b296e32016-04-25 19:09:05 +00001604 // When Arg cannot be a derived class, we can just try to deduce template
1605 // arguments from the template-id.
1606 const RecordType *RecordT = Arg->getAs<RecordType>();
1607 if (!(TDF & TDF_DerivedClass) || !RecordT)
1608 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1609 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001610
Richard Smith9b296e32016-04-25 19:09:05 +00001611 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1612 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001613
Richard Smith9b296e32016-04-25 19:09:05 +00001614 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1615 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001616
Richard Smith9b296e32016-04-25 19:09:05 +00001617 if (Result == Sema::TDK_Success)
1618 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001619
Richard Smith9b296e32016-04-25 19:09:05 +00001620 // We cannot inspect base classes as part of deduction when the type
1621 // is incomplete, so either instantiate any templates necessary to
1622 // complete the type, or skip over it if it cannot be completed.
1623 if (!S.isCompleteType(Info.getLocation(), Arg))
1624 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001625
Richard Smith9b296e32016-04-25 19:09:05 +00001626 // C++14 [temp.deduct.call] p4b3:
1627 // If P is a class and P has the form simple-template-id, then the
1628 // transformed A can be a derived class of the deduced A. Likewise if
1629 // P is a pointer to a class of the form simple-template-id, the
1630 // transformed A can be a pointer to a derived class pointed to by the
1631 // deduced A.
1632 //
1633 // These alternatives are considered only if type deduction would
1634 // otherwise fail. If they yield more than one possible deduced A, the
1635 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001636
Faisal Vali683b0742016-05-19 02:28:21 +00001637 // Reset the incorrectly deduced argument from above.
1638 Deduced = DeducedOrig;
1639
1640 // Use data recursion to crawl through the list of base classes.
1641 // Visited contains the set of nodes we have already visited, while
1642 // ToVisit is our stack of records that we still need to visit.
1643 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1644 SmallVector<const RecordType *, 8> ToVisit;
1645 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001646 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001647 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001648 while (!ToVisit.empty()) {
1649 // Retrieve the next class in the inheritance hierarchy.
1650 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001651
Faisal Vali683b0742016-05-19 02:28:21 +00001652 // If we have already seen this type, skip it.
1653 if (!Visited.insert(NextT).second)
1654 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001655
Faisal Vali683b0742016-05-19 02:28:21 +00001656 // If this is a base class, try to perform template argument
1657 // deduction from it.
1658 if (NextT != RecordT) {
1659 TemplateDeductionInfo BaseInfo(Info.getLocation());
1660 Sema::TemplateDeductionResult BaseResult =
1661 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1662 QualType(NextT, 0), BaseInfo, Deduced);
1663
1664 // If template argument deduction for this base was successful,
1665 // note that we had some success. Otherwise, ignore any deductions
1666 // from this base class.
1667 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001668 // If we've already seen some success, then deduction fails due to
1669 // an ambiguity (temp.deduct.call p5).
1670 if (Successful)
1671 return Sema::TDK_MiscellaneousDeductionFailure;
1672
Faisal Vali683b0742016-05-19 02:28:21 +00001673 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001674 std::swap(SuccessfulDeduced, Deduced);
1675
Faisal Vali683b0742016-05-19 02:28:21 +00001676 Info.Param = BaseInfo.Param;
1677 Info.FirstArg = BaseInfo.FirstArg;
1678 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001679 }
1680
1681 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001682 }
Mike Stump11289f42009-09-09 15:08:12 +00001683
Faisal Vali683b0742016-05-19 02:28:21 +00001684 // Visit base classes
1685 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1686 for (const auto &Base : Next->bases()) {
1687 assert(Base.getType()->isRecordType() &&
1688 "Base class that isn't a record?");
1689 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1690 }
1691 }
Mike Stump11289f42009-09-09 15:08:12 +00001692
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001693 if (Successful) {
1694 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001695 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001696 }
Richard Smith9b296e32016-04-25 19:09:05 +00001697
Douglas Gregore81f3e72009-07-07 23:09:34 +00001698 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001699 }
1700
Douglas Gregor637d9982009-06-10 23:47:09 +00001701 // T type::*
1702 // T T::*
1703 // T (type::*)()
1704 // type (T::*)()
1705 // type (type::*)(T)
1706 // type (T::*)(T)
1707 // T (type::*)(T)
1708 // T (T::*)()
1709 // T (T::*)(T)
1710 case Type::MemberPointer: {
1711 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1712 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1713 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001714 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001715
David Majnemera381cda2015-11-30 20:34:28 +00001716 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1717 if (ParamPointeeType->isFunctionType())
1718 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1719 /*IsCtorOrDtor=*/false, Info.getLocation());
1720 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1721 if (ArgPointeeType->isFunctionType())
1722 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1723 /*IsCtorOrDtor=*/false, Info.getLocation());
1724
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001725 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001726 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001727 ParamPointeeType,
1728 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001729 Info, Deduced,
1730 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001731 return Result;
1732
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001733 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1734 QualType(MemPtrParam->getClass(), 0),
1735 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001736 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001737 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001738 }
1739
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001740 // (clang extension)
1741 //
Mike Stump11289f42009-09-09 15:08:12 +00001742 // type(^)(T)
1743 // T(^)()
1744 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001745 case Type::BlockPointer: {
1746 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1747 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001748
Anders Carlssona767eee2009-06-12 16:23:10 +00001749 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001750 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001751
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001752 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1753 BlockPtrParam->getPointeeType(),
1754 BlockPtrArg->getPointeeType(),
1755 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001756 }
1757
Douglas Gregor39c02722011-06-15 16:02:29 +00001758 // (clang extension)
1759 //
1760 // T __attribute__(((ext_vector_type(<integral constant>))))
1761 case Type::ExtVector: {
1762 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1763 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1764 // Make sure that the vectors have the same number of elements.
1765 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1766 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001767
Douglas Gregor39c02722011-06-15 16:02:29 +00001768 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001769 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1770 VectorParam->getElementType(),
1771 VectorArg->getElementType(),
1772 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001773 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001774
1775 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001776 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1777 // We can't check the number of elements, since the argument has a
1778 // dependent number of elements. This can only occur during partial
1779 // ordering.
1780
1781 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001782 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1783 VectorParam->getElementType(),
1784 VectorArg->getElementType(),
1785 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001786 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001787
Douglas Gregor39c02722011-06-15 16:02:29 +00001788 return Sema::TDK_NonDeducedMismatch;
1789 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001790
Douglas Gregor39c02722011-06-15 16:02:29 +00001791 // (clang extension)
1792 //
1793 // T __attribute__(((ext_vector_type(N))))
1794 case Type::DependentSizedExtVector: {
1795 const DependentSizedExtVectorType *VectorParam
1796 = cast<DependentSizedExtVectorType>(Param);
1797
1798 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1799 // Perform deduction on the element types.
1800 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001801 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1802 VectorParam->getElementType(),
1803 VectorArg->getElementType(),
1804 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001805 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001806
Douglas Gregor39c02722011-06-15 16:02:29 +00001807 // Perform deduction on the vector size, if we can.
1808 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001809 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001810 if (!NTTP)
1811 return Sema::TDK_Success;
1812
1813 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1814 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001815 // Note that we use the "array bound" rules here; just like in that
1816 // case, we don't have any particular type for the vector size, but
1817 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001818 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001819 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001820 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001821 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001822
1823 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001824 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1825 // Perform deduction on the element types.
1826 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001827 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1828 VectorParam->getElementType(),
1829 VectorArg->getElementType(),
1830 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001831 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001832
Douglas Gregor39c02722011-06-15 16:02:29 +00001833 // Perform deduction on the vector size, if we can.
1834 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001835 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001836 if (!NTTP)
1837 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001838
Richard Smith5f274382016-09-28 23:55:27 +00001839 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1840 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001841 Info, Deduced);
1842 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001843
Douglas Gregor39c02722011-06-15 16:02:29 +00001844 return Sema::TDK_NonDeducedMismatch;
1845 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001846
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001847 // (clang extension)
1848 //
1849 // T __attribute__(((address_space(N))))
1850 case Type::DependentAddressSpace: {
1851 const DependentAddressSpaceType *AddressSpaceParam =
1852 cast<DependentAddressSpaceType>(Param);
1853
1854 if (const DependentAddressSpaceType *AddressSpaceArg =
1855 dyn_cast<DependentAddressSpaceType>(Arg)) {
1856 // Perform deduction on the pointer type.
1857 if (Sema::TemplateDeductionResult Result =
1858 DeduceTemplateArgumentsByTypeMatch(
1859 S, TemplateParams, AddressSpaceParam->getPointeeType(),
1860 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
1861 return Result;
1862
1863 // Perform deduction on the address space, if we can.
1864 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1865 Info, AddressSpaceParam->getAddrSpaceExpr());
1866 if (!NTTP)
1867 return Sema::TDK_Success;
1868
1869 return DeduceNonTypeTemplateArgument(
1870 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
1871 Deduced);
1872 }
1873
Alexander Richardson6d989432017-10-15 18:48:14 +00001874 if (isTargetAddressSpace(Arg.getAddressSpace())) {
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001875 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
1876 false);
Alexander Richardson6d989432017-10-15 18:48:14 +00001877 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001878
1879 // Perform deduction on the pointer types.
1880 if (Sema::TemplateDeductionResult Result =
1881 DeduceTemplateArgumentsByTypeMatch(
1882 S, TemplateParams, AddressSpaceParam->getPointeeType(),
1883 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
1884 return Result;
1885
1886 // Perform deduction on the address space, if we can.
1887 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1888 Info, AddressSpaceParam->getAddrSpaceExpr());
1889 if (!NTTP)
1890 return Sema::TDK_Success;
1891
1892 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1893 ArgAddressSpace, S.Context.IntTy,
1894 true, Info, Deduced);
1895 }
1896
1897 return Sema::TDK_NonDeducedMismatch;
1898 }
1899
Douglas Gregor637d9982009-06-10 23:47:09 +00001900 case Type::TypeOfExpr:
1901 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001902 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001903 case Type::UnresolvedUsing:
1904 case Type::Decltype:
1905 case Type::UnaryTransform:
1906 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001907 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001908 case Type::DependentTemplateSpecialization:
1909 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001910 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001911 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001912 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001913 }
1914
David Blaikiee4d798f2012-01-20 21:50:17 +00001915 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001916}
1917
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001918static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001919DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001920 TemplateParameterList *TemplateParams,
1921 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001922 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001923 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001924 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001925 // If the template argument is a pack expansion, perform template argument
1926 // deduction against the pattern of that expansion. This only occurs during
1927 // partial ordering.
1928 if (Arg.isPackExpansion())
1929 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001931 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001932 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001933 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001934
1935 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001936 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001937 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1938 Param.getAsType(),
1939 Arg.getAsType(),
1940 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001941 Info.FirstArg = Param;
1942 Info.SecondArg = Arg;
1943 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001944
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001945 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001946 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001948 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001949 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001950 Info.FirstArg = Param;
1951 Info.SecondArg = Arg;
1952 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001953
1954 case TemplateArgument::TemplateExpansion:
1955 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001957 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001958 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001959 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001960 return Sema::TDK_Success;
1961
1962 Info.FirstArg = Param;
1963 Info.SecondArg = Arg;
1964 return Sema::TDK_NonDeducedMismatch;
1965
1966 case TemplateArgument::NullPtr:
1967 if (Arg.getKind() == TemplateArgument::NullPtr &&
1968 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001969 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001971 Info.FirstArg = Param;
1972 Info.SecondArg = Arg;
1973 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001975 case TemplateArgument::Integral:
1976 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001977 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001978 return Sema::TDK_Success;
1979
1980 Info.FirstArg = Param;
1981 Info.SecondArg = Arg;
1982 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001983 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001984
1985 if (Arg.getKind() == TemplateArgument::Expression) {
1986 Info.FirstArg = Param;
1987 Info.SecondArg = Arg;
1988 return Sema::TDK_NonDeducedMismatch;
1989 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001990
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001991 Info.FirstArg = Param;
1992 Info.SecondArg = Arg;
1993 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001994
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001995 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001996 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001997 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001998 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001999 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002000 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00002001 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002002 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002003 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00002004 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00002005 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2006 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00002007 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002008 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00002009 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2010 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002011 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00002012 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2013 Arg.getAsDecl(),
2014 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002015 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002017 Info.FirstArg = Param;
2018 Info.SecondArg = Arg;
2019 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002022 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002023 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002024 }
Anders Carlssonbc343912009-06-15 17:04:53 +00002025 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00002026 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
David Blaikiee4d798f2012-01-20 21:50:17 +00002029 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002030}
2031
Douglas Gregor7baabef2010-12-22 18:17:10 +00002032/// \brief Determine whether there is a template argument to be used for
2033/// deduction.
2034///
2035/// This routine "expands" argument packs in-place, overriding its input
2036/// parameters so that \c Args[ArgIdx] will be the available template argument.
2037///
2038/// \returns true if there is another template argument (which will be at
2039/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00002040static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2041 unsigned &ArgIdx) {
2042 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00002043 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002044
Douglas Gregor7baabef2010-12-22 18:17:10 +00002045 const TemplateArgument &Arg = Args[ArgIdx];
2046 if (Arg.getKind() != TemplateArgument::Pack)
2047 return true;
2048
Richard Smith0bda5b52016-12-23 23:46:56 +00002049 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2050 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002051 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002052 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002053}
2054
Douglas Gregord0ad2942010-12-23 01:24:45 +00002055/// \brief Determine whether the given set of template arguments has a pack
2056/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002057static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2058 bool FoundPackExpansion = false;
2059 for (const auto &A : Args) {
2060 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002061 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002062
2063 if (A.getKind() == TemplateArgument::Pack)
2064 return hasPackExpansionBeforeEnd(A.pack_elements());
2065
2066 if (A.isPackExpansion())
2067 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Douglas Gregord0ad2942010-12-23 01:24:45 +00002070 return false;
2071}
2072
Douglas Gregor7baabef2010-12-22 18:17:10 +00002073static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002074DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002075 ArrayRef<TemplateArgument> Params,
2076 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002077 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002078 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2079 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002080 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081 // If the template argument list of P contains a pack expansion that is not
2082 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002083 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002084 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002085 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002087 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002088 // If P has a form that contains <T> or <i>, then each argument Pi of the
2089 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002090 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002091 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002092 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002093 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002094 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Douglas Gregor7baabef2010-12-22 18:17:10 +00002096 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002097 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002098 return NumberOfArgumentsMustMatch
2099 ? Sema::TDK_MiscellaneousDeductionFailure
2100 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
Richard Smith26b86ea2016-12-31 21:41:23 +00002102 // C++1z [temp.deduct.type]p9:
2103 // During partial ordering, if Ai was originally a pack expansion [and]
2104 // Pi is not a pack expansion, template argument deduction fails.
2105 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002106 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002108 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002109 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002110 = DeduceTemplateArguments(S, TemplateParams,
2111 Params[ParamIdx], Args[ArgIdx],
2112 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002113 return Result;
2114
Douglas Gregor7baabef2010-12-22 18:17:10 +00002115 // Move to the next argument.
2116 ++ArgIdx;
2117 continue;
2118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002120 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002122 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123 // If Pi is a pack expansion, then the pattern of Pi is compared with
2124 // each remaining argument in the template argument list of A. Each
2125 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002126 // template parameter packs expanded by Pi.
2127 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002129 // FIXME: If there are no remaining arguments, we can bail out early
2130 // and set any deduced parameter packs to an empty argument pack.
2131 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132
Richard Smith0a80d572014-05-29 01:12:14 +00002133 // Prepare to deduce the packs within the pattern.
2134 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002135
2136 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002138 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00002139 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002140 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002142 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2143 Info, Deduced))
2144 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145
Richard Smith0a80d572014-05-29 01:12:14 +00002146 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002149 // Build argument packs for each of the parameter packs expanded by this
2150 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002151 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregor7baabef2010-12-22 18:17:10 +00002155 return Sema::TDK_Success;
2156}
2157
Mike Stump11289f42009-09-09 15:08:12 +00002158static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002159DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002160 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002161 const TemplateArgumentList &ParamList,
2162 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002163 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002164 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002165 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002166 ArgList.asArray(), Info, Deduced,
2167 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002168}
2169
Douglas Gregor705c9002009-06-26 20:57:09 +00002170/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002171static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002172 TemplateArgument X,
2173 const TemplateArgument &Y,
2174 bool PackExpansionMatchesPack = false) {
2175 // If we're checking deduced arguments (X) against original arguments (Y),
2176 // we will have flattened packs to non-expansions in X.
2177 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2178 X = X.getPackExpansionPattern();
2179
Douglas Gregor705c9002009-06-26 20:57:09 +00002180 if (X.getKind() != Y.getKind())
2181 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002182
Douglas Gregor705c9002009-06-26 20:57:09 +00002183 switch (X.getKind()) {
2184 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002185 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002186
Douglas Gregor705c9002009-06-26 20:57:09 +00002187 case TemplateArgument::Type:
2188 return Context.getCanonicalType(X.getAsType()) ==
2189 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002190
Douglas Gregor705c9002009-06-26 20:57:09 +00002191 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002192 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002193
2194 case TemplateArgument::NullPtr:
2195 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002197 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002198 case TemplateArgument::TemplateExpansion:
2199 return Context.getCanonicalTemplateName(
2200 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2201 Context.getCanonicalTemplateName(
2202 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203
Douglas Gregor705c9002009-06-26 20:57:09 +00002204 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002205 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002206
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002207 case TemplateArgument::Expression: {
2208 llvm::FoldingSetNodeID XID, YID;
2209 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002211 return XID == YID;
2212 }
Mike Stump11289f42009-09-09 15:08:12 +00002213
Douglas Gregor705c9002009-06-26 20:57:09 +00002214 case TemplateArgument::Pack:
2215 if (X.pack_size() != Y.pack_size())
2216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002217
2218 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2219 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002220 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002221 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002222 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002223 return false;
2224
2225 return true;
2226 }
2227
David Blaikiee4d798f2012-01-20 21:50:17 +00002228 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002229}
2230
Douglas Gregorca4686d2011-01-04 23:35:54 +00002231/// \brief Allocate a TemplateArgumentLoc where all locations have
2232/// been initialized to the given location.
2233///
James Dennett634962f2012-06-14 21:40:34 +00002234/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002235/// location information for.
2236///
2237/// \param NTTPType For a declaration template argument, the type of
2238/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002239/// argument. Can be null if no type sugar is available to add to the
2240/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002241///
2242/// \param Loc The source location to use for the resulting template
2243/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002244TemplateArgumentLoc
2245Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2246 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002247 switch (Arg.getKind()) {
2248 case TemplateArgument::Null:
2249 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002250
Douglas Gregorca4686d2011-01-04 23:35:54 +00002251 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002252 return TemplateArgumentLoc(
2253 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002254
Douglas Gregorca4686d2011-01-04 23:35:54 +00002255 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002256 if (NTTPType.isNull())
2257 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002258 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2259 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002260 return TemplateArgumentLoc(TemplateArgument(E), E);
2261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262
Eli Friedmanb826a002012-09-26 02:36:12 +00002263 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002264 if (NTTPType.isNull())
2265 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002266 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2267 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002268 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2269 E);
2270 }
2271
Douglas Gregorca4686d2011-01-04 23:35:54 +00002272 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002273 Expr *E =
2274 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002275 return TemplateArgumentLoc(TemplateArgument(E), E);
2276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277
Douglas Gregor9d802122011-03-02 17:09:35 +00002278 case TemplateArgument::Template:
2279 case TemplateArgument::TemplateExpansion: {
2280 NestedNameSpecifierLocBuilder Builder;
2281 TemplateName Template = Arg.getAsTemplate();
2282 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002283 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002284 else if (QualifiedTemplateName *QTN =
2285 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002286 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002287
Douglas Gregor9d802122011-03-02 17:09:35 +00002288 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002289 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002290 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002291
2292 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002293 Loc, Loc);
2294 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002295
Douglas Gregorca4686d2011-01-04 23:35:54 +00002296 case TemplateArgument::Expression:
2297 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
Douglas Gregorca4686d2011-01-04 23:35:54 +00002299 case TemplateArgument::Pack:
2300 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302
David Blaikiee4d798f2012-01-20 21:50:17 +00002303 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002304}
2305
2306
2307/// \brief Convert the given deduced template argument and add it to the set of
2308/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002309static bool
2310ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2311 DeducedTemplateArgument Arg,
2312 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002313 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002314 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002315 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002316 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2317 unsigned ArgumentPackIndex) {
2318 // Convert the deduced template argument into a template
2319 // argument that we can check, almost as if the user had written
2320 // the template argument explicitly.
2321 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002322 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002323
2324 // Check the template argument, converting it as necessary.
2325 return S.CheckTemplateArgument(
2326 Param, ArgLoc, Template, Template->getLocation(),
2327 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002328 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002329 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2330 : Sema::CTAK_Deduced)
2331 : Sema::CTAK_Specified);
2332 };
2333
Douglas Gregorca4686d2011-01-04 23:35:54 +00002334 if (Arg.getKind() == TemplateArgument::Pack) {
2335 // This is a template argument pack, so check each of its arguments against
2336 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002337 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002338 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002339 // When converting the deduced template argument, append it to the
2340 // general output list. We need to do this so that the template argument
2341 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002342 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002343 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002344 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2345 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002346 if (P.isNull()) {
2347 // We deduced arguments for some elements of this pack, but not for
2348 // all of them. This happens if we get a conditionally-non-deduced
2349 // context in a pack expansion (such as an overload set in one of the
2350 // arguments).
2351 S.Diag(Param->getLocation(),
2352 diag::err_template_arg_deduced_incomplete_pack)
2353 << Arg << Param;
2354 return true;
2355 }
Richard Smith37acb792016-02-03 20:15:01 +00002356 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002357 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002358
Douglas Gregor51bc5712011-01-05 20:52:18 +00002359 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002360 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002362
Richard Smithdf18ee92016-02-03 20:40:30 +00002363 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002364 // itself, in case that substitution fails.
2365 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002366 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002367 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002368 MultiLevelTemplateArgumentList Args(TemplateArgs);
2369
2370 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2371 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2372 NTTP, Output,
2373 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002374 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002375 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2376 NTTP->getDeclName()).isNull())
2377 return true;
2378 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2379 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2380 TTP, Output,
2381 Template->getSourceRange());
2382 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2383 return true;
2384 }
2385 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002386 }
Richard Smith37acb792016-02-03 20:15:01 +00002387
Douglas Gregorca4686d2011-01-04 23:35:54 +00002388 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002389 Output.push_back(
2390 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002391 return false;
2392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002393
Richard Smith37acb792016-02-03 20:15:01 +00002394 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002395}
2396
Richard Smith1f5be4d2016-12-21 01:10:31 +00002397// FIXME: This should not be a template, but
2398// ClassTemplatePartialSpecializationDecl sadly does not derive from
2399// TemplateDecl.
2400template<typename TemplateDeclT>
2401static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002402 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002403 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2404 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2405 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002406 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002407 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2408
2409 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2410 NamedDecl *Param = TemplateParams->getParam(I);
2411
2412 if (!Deduced[I].isNull()) {
2413 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002414 // We may have had explicitly-specified template arguments for a
2415 // template parameter pack (that may or may not have been extended
2416 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002417 if (Param->isParameterPack() && CurrentInstantiationScope &&
2418 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2419 // Forget the partially-substituted pack; its substitution is now
2420 // complete.
2421 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2422 // We still need to check the argument in case it was extended by
2423 // deduction.
2424 } else {
2425 // We have already fully type-checked and converted this
2426 // argument, because it was explicitly-specified. Just record the
2427 // presence of this argument.
2428 Builder.push_back(Deduced[I]);
2429 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002430 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002431 }
2432
Richard Smith9c0c9862017-01-05 20:27:28 +00002433 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002434 // checked and converted.
2435 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002436 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002437 Info.Param = makeTemplateParameter(Param);
2438 // FIXME: These template arguments are temporary. Free them!
2439 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2440 return Sema::TDK_SubstitutionFailure;
2441 }
2442
2443 continue;
2444 }
2445
2446 // C++0x [temp.arg.explicit]p3:
2447 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2448 // be deduced to an empty sequence of template arguments.
2449 // FIXME: Where did the word "trailing" come from?
2450 if (Param->isTemplateParameterPack()) {
2451 // We may have had explicitly-specified template arguments for this
2452 // template parameter pack. If so, our empty deduction extends the
2453 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2454 const TemplateArgument *ExplicitArgs;
2455 unsigned NumExplicitArgs;
2456 if (CurrentInstantiationScope &&
2457 CurrentInstantiationScope->getPartiallySubstitutedPack(
2458 &ExplicitArgs, &NumExplicitArgs) == Param) {
2459 Builder.push_back(TemplateArgument(
2460 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2461
2462 // Forget the partially-substituted pack; its substitution is now
2463 // complete.
2464 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2465 } else {
2466 // Go through the motions of checking the empty argument pack against
2467 // the parameter pack.
2468 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002469 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2470 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002471 Info.Param = makeTemplateParameter(Param);
2472 // FIXME: These template arguments are temporary. Free them!
2473 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2474 return Sema::TDK_SubstitutionFailure;
2475 }
2476 }
2477 continue;
2478 }
2479
2480 // Substitute into the default template argument, if available.
2481 bool HasDefaultArg = false;
2482 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2483 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002484 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2485 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002486 return Sema::TDK_Incomplete;
2487 }
2488
2489 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2490 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2491 HasDefaultArg);
2492
2493 // If there was no default argument, deduction is incomplete.
2494 if (DefArg.getArgument().isNull()) {
2495 Info.Param = makeTemplateParameter(
2496 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2497 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002498 if (PartialOverloading) break;
2499
Richard Smith1f5be4d2016-12-21 01:10:31 +00002500 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2501 : Sema::TDK_Incomplete;
2502 }
2503
2504 // Check whether we can actually use the default argument.
2505 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2506 TD->getSourceRange().getEnd(), 0, Builder,
2507 Sema::CTAK_Specified)) {
2508 Info.Param = makeTemplateParameter(
2509 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2510 // FIXME: These template arguments are temporary. Free them!
2511 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2512 return Sema::TDK_SubstitutionFailure;
2513 }
2514
2515 // If we get here, we successfully used the default template argument.
2516 }
2517
2518 return Sema::TDK_Success;
2519}
2520
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002521static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002522 if (auto *DC = dyn_cast<DeclContext>(D))
2523 return DC;
2524 return D->getDeclContext();
2525}
2526
2527template<typename T> struct IsPartialSpecialization {
2528 static constexpr bool value = false;
2529};
2530template<>
2531struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2532 static constexpr bool value = true;
2533};
2534template<>
2535struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2536 static constexpr bool value = true;
2537};
2538
2539/// Complete template argument deduction for a partial specialization.
2540template <typename T>
2541static typename std::enable_if<IsPartialSpecialization<T>::value,
2542 Sema::TemplateDeductionResult>::type
2543FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002544 Sema &S, T *Partial, bool IsPartialOrdering,
2545 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002546 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2547 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002548 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002549 EnterExpressionEvaluationContext Unevaluated(
2550 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002551 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552
Richard Smith0da6dc42016-12-24 16:40:51 +00002553 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002554
2555 // C++ [temp.deduct.type]p2:
2556 // [...] or if any template argument remains neither deduced nor
2557 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002558 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002559 if (auto Result = ConvertDeducedTemplateArguments(
2560 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002561 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562
Douglas Gregor684268d2010-04-29 06:21:43 +00002563 // Form the template argument list from the deduced template arguments.
2564 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002565 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002566
Douglas Gregor684268d2010-04-29 06:21:43 +00002567 Info.reset(DeducedArgumentList);
2568
2569 // Substitute the deduced template arguments into the template
2570 // arguments of the class template partial specialization, and
2571 // verify that the instantiated template arguments are both valid
2572 // and are equivalent to the template arguments originally provided
2573 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002574 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002575 auto *Template = Partial->getSpecializedTemplate();
2576 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2577 Partial->getTemplateArgsAsWritten();
2578 const TemplateArgumentLoc *PartialTemplateArgs =
2579 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002580
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002581 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2582 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002583
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002584 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002585 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2586 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2587 if (ParamIdx >= Partial->getTemplateParameters()->size())
2588 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2589
Richard Smith0da6dc42016-12-24 16:40:51 +00002590 Decl *Param = const_cast<NamedDecl *>(
2591 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002592 Info.Param = makeTemplateParameter(Param);
2593 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2594 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002595 }
2596
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002598 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2599 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002600 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002601
Richard Smith0da6dc42016-12-24 16:40:51 +00002602 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002603 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002604 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002605 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002606 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002607 Info.FirstArg = TemplateArgs[I];
2608 Info.SecondArg = InstArg;
2609 return Sema::TDK_NonDeducedMismatch;
2610 }
2611 }
2612
2613 if (Trap.hasErrorOccurred())
2614 return Sema::TDK_SubstitutionFailure;
2615
2616 return Sema::TDK_Success;
2617}
2618
Richard Smith0e617ec2016-12-27 07:56:27 +00002619/// Complete template argument deduction for a class or variable template,
2620/// when partial ordering against a partial specialization.
2621// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002622static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002623 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2624 const TemplateArgumentList &TemplateArgs,
2625 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2626 TemplateDeductionInfo &Info) {
2627 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002628 EnterExpressionEvaluationContext Unevaluated(
2629 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002630 Sema::SFINAETrap Trap(S);
2631
2632 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2633
2634 // C++ [temp.deduct.type]p2:
2635 // [...] or if any template argument remains neither deduced nor
2636 // explicitly specified, template argument deduction fails.
2637 SmallVector<TemplateArgument, 4> Builder;
2638 if (auto Result = ConvertDeducedTemplateArguments(
2639 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2640 return Result;
2641
2642 // Check that we produced the correct argument list.
2643 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2644 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2645 TemplateArgument InstArg = Builder[I];
2646 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2647 /*PackExpansionMatchesPack*/true)) {
2648 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2649 Info.FirstArg = TemplateArgs[I];
2650 Info.SecondArg = InstArg;
2651 return Sema::TDK_NonDeducedMismatch;
2652 }
2653 }
2654
2655 if (Trap.hasErrorOccurred())
2656 return Sema::TDK_SubstitutionFailure;
2657
2658 return Sema::TDK_Success;
2659}
2660
2661
Douglas Gregor170bc422009-06-12 22:31:52 +00002662/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002663/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002664/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002665Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002666Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002667 const TemplateArgumentList &TemplateArgs,
2668 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002669 if (Partial->isInvalidDecl())
2670 return TDK_Invalid;
2671
Douglas Gregor170bc422009-06-12 22:31:52 +00002672 // C++ [temp.class.spec.match]p2:
2673 // A partial specialization matches a given actual template
2674 // argument list if the template arguments of the partial
2675 // specialization can be deduced from the actual template argument
2676 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002677
2678 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002679 EnterExpressionEvaluationContext Unevaluated(
2680 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002681 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002682
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002683 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002684 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002685 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002686 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002687 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002688 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002689 TemplateArgs, Info, Deduced))
2690 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002691
Richard Smith80934652012-07-16 01:09:10 +00002692 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002693 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2694 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002695 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002696 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002697
Douglas Gregore1416332009-06-14 08:02:22 +00002698 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002699 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700
Richard Smith87d263e2016-12-25 08:05:23 +00002701 return ::FinishTemplateArgumentDeduction(
2702 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002703}
Douglas Gregor91772d12009-06-13 00:26:55 +00002704
Larisse Voufo39a1e502013-08-06 01:03:05 +00002705/// \brief Perform template argument deduction to determine whether
2706/// the given template arguments match the given variable template
2707/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002708Sema::TemplateDeductionResult
2709Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2710 const TemplateArgumentList &TemplateArgs,
2711 TemplateDeductionInfo &Info) {
2712 if (Partial->isInvalidDecl())
2713 return TDK_Invalid;
2714
2715 // C++ [temp.class.spec.match]p2:
2716 // A partial specialization matches a given actual template
2717 // argument list if the template arguments of the partial
2718 // specialization can be deduced from the actual template argument
2719 // list (14.8.2).
2720
2721 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002722 EnterExpressionEvaluationContext Unevaluated(
2723 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002724 SFINAETrap Trap(*this);
2725
2726 SmallVector<DeducedTemplateArgument, 4> Deduced;
2727 Deduced.resize(Partial->getTemplateParameters()->size());
2728 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2729 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2730 TemplateArgs, Info, Deduced))
2731 return Result;
2732
2733 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002734 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2735 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002736 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002737 return TDK_InstantiationDepth;
2738
2739 if (Trap.hasErrorOccurred())
2740 return Sema::TDK_SubstitutionFailure;
2741
Richard Smith87d263e2016-12-25 08:05:23 +00002742 return ::FinishTemplateArgumentDeduction(
2743 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002744}
2745
Douglas Gregorfc516c92009-06-26 23:27:24 +00002746/// \brief Determine whether the given type T is a simple-template-id type.
2747static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002748 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002749 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002750 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002751
Richard Smith1363e8f2017-09-07 07:22:36 +00002752 // C++17 [temp.local]p2:
2753 // the injected-class-name [...] is equivalent to the template-name followed
2754 // by the template-arguments of the class template specialization or partial
2755 // specialization enclosed in <>
2756 // ... which means it's equivalent to a simple-template-id.
2757 //
2758 // This only arises during class template argument deduction for a copy
2759 // deduction candidate, where it permits slicing.
2760 if (T->getAs<InjectedClassNameType>())
2761 return true;
2762
Douglas Gregorfc516c92009-06-26 23:27:24 +00002763 return false;
2764}
Douglas Gregor9b146582009-07-08 20:55:45 +00002765
2766/// \brief Substitute the explicitly-provided template arguments into the
2767/// given function template according to C++ [temp.arg.explicit].
2768///
2769/// \param FunctionTemplate the function template into which the explicit
2770/// template arguments will be substituted.
2771///
James Dennett634962f2012-06-14 21:40:34 +00002772/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002773/// arguments.
2774///
Mike Stump11289f42009-09-09 15:08:12 +00002775/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002776/// with the converted and checked explicit template arguments.
2777///
Mike Stump11289f42009-09-09 15:08:12 +00002778/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002779/// parameters.
2780///
2781/// \param FunctionType if non-NULL, the result type of the function template
2782/// will also be instantiated and the pointed-to value will be updated with
2783/// the instantiated function type.
2784///
2785/// \param Info if substitution fails for any reason, this object will be
2786/// populated with more information about the failure.
2787///
2788/// \returns TDK_Success if substitution was successful, or some failure
2789/// condition.
2790Sema::TemplateDeductionResult
2791Sema::SubstituteExplicitTemplateArguments(
2792 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002793 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2795 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002796 QualType *FunctionType,
2797 TemplateDeductionInfo &Info) {
2798 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2799 TemplateParameterList *TemplateParams
2800 = FunctionTemplate->getTemplateParameters();
2801
John McCall6b51f282009-11-23 01:53:49 +00002802 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002803 // No arguments to substitute; just copy over the parameter types and
2804 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002805 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002806 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002807
Douglas Gregor9b146582009-07-08 20:55:45 +00002808 if (FunctionType)
2809 *FunctionType = Function->getType();
2810 return TDK_Success;
2811 }
Mike Stump11289f42009-09-09 15:08:12 +00002812
Eli Friedman77dcc722012-02-08 03:07:05 +00002813 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002814 EnterExpressionEvaluationContext Unevaluated(
2815 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002816 SFINAETrap Trap(*this);
2817
Douglas Gregor9b146582009-07-08 20:55:45 +00002818 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002819 // Template arguments that are present shall be specified in the
2820 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002821 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002822 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002823 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002824
2825 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002826 // explicitly-specified template arguments against this function template,
2827 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002828 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00002829 InstantiatingTemplate Inst(
2830 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2831 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002832 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002833 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002834
Richard Smith11255ec2017-01-18 19:19:22 +00002835 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2836 ExplicitTemplateArgs, true, Builder, false) ||
2837 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002838 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002839 if (Index >= TemplateParams->size())
2840 Index = TemplateParams->size() - 1;
2841 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002842 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002843 }
Mike Stump11289f42009-09-09 15:08:12 +00002844
Douglas Gregor9b146582009-07-08 20:55:45 +00002845 // Form the template argument list from the explicitly-specified
2846 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002847 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002848 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002849 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850
John McCall036855a2010-10-12 19:40:14 +00002851 // Template argument deduction and the final substitution should be
2852 // done in the context of the templated declaration. Explicit
2853 // argument substitution, on the other hand, needs to happen in the
2854 // calling context.
2855 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2856
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002858 // note that the template argument pack is partially substituted and record
2859 // the explicit template arguments. They'll be used as part of deduction
2860 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002861 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2862 const TemplateArgument &Arg = Builder[I];
2863 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002864 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002866 Arg.pack_begin(),
2867 Arg.pack_size());
2868 break;
2869 }
2870 }
2871
Richard Smith5e580292012-02-10 09:58:53 +00002872 const FunctionProtoType *Proto
2873 = Function->getType()->getAs<FunctionProtoType>();
2874 assert(Proto && "Function template does not have a prototype?");
2875
Richard Smith70b13042015-01-09 01:19:56 +00002876 // Isolate our substituted parameters from our caller.
2877 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2878
John McCallc8e321d2016-03-01 02:09:25 +00002879 ExtParameterInfoBuilder ExtParamInfos;
2880
Douglas Gregor9b146582009-07-08 20:55:45 +00002881 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002882 // explicitly-specified template arguments. If the function has a trailing
2883 // return type, substitute it after the arguments to ensure we substitute
2884 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002885 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002886 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002887 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002888 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002889 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002890 return TDK_SubstitutionFailure;
2891 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002892
Richard Smith5e580292012-02-10 09:58:53 +00002893 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002894 QualType ResultType;
2895 {
2896 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002897 // If a declaration declares a member function or member function
2898 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002899 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002900 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002901 // declarator.
2902 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002903 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2905 ThisContext = Method->getParent();
2906 ThisTypeQuals = Method->getTypeQualifiers();
2907 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002908
Douglas Gregor3024f072012-04-16 07:05:22 +00002909 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002910 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002911
2912 ResultType =
2913 SubstType(Proto->getReturnType(),
2914 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2915 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002916 if (ResultType.isNull() || Trap.hasErrorOccurred())
2917 return TDK_SubstitutionFailure;
2918 }
John McCallc8e321d2016-03-01 02:09:25 +00002919
Richard Smith5e580292012-02-10 09:58:53 +00002920 // Instantiate the types of each of the function parameters given the
2921 // explicitly-specified template arguments if we didn't do so earlier.
2922 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002923 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002924 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002925 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002926 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002927 return TDK_SubstitutionFailure;
2928
Douglas Gregor9b146582009-07-08 20:55:45 +00002929 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002930 auto EPI = Proto->getExtProtoInfo();
2931 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00002932
2933 // In C++1z onwards, exception specifications are part of the function type,
2934 // so substitution into the type must also substitute into the exception
2935 // specification.
2936 SmallVector<QualType, 4> ExceptionStorage;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002937 if (getLangOpts().CPlusPlus17 &&
Richard Smithcd198152017-06-07 21:46:22 +00002938 SubstExceptionSpec(
2939 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
2940 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
2941 return TDK_SubstitutionFailure;
2942
Jordan Rose5c382722013-03-08 21:51:21 +00002943 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002944 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002945 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002946 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002947 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2948 return TDK_SubstitutionFailure;
2949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregor9b146582009-07-08 20:55:45 +00002951 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002952 // Trailing template arguments that can be deduced (14.8.2) may be
2953 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002954 // template arguments can be deduced, they may all be omitted; in this
2955 // case, the empty template argument list <> itself may also be omitted.
2956 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002957 // Take all of the explicitly-specified arguments and put them into
2958 // the set of deduced template arguments. Explicitly-specified
2959 // parameter packs, however, will be set to NULL since the deduction
2960 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002961 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002962 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2963 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2964 if (Arg.getKind() == TemplateArgument::Pack)
2965 Deduced.push_back(DeducedTemplateArgument());
2966 else
2967 Deduced.push_back(Arg);
2968 }
Mike Stump11289f42009-09-09 15:08:12 +00002969
Douglas Gregor9b146582009-07-08 20:55:45 +00002970 return TDK_Success;
2971}
2972
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002973/// \brief Check whether the deduced argument type for a call to a function
2974/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00002975static Sema::TemplateDeductionResult
2976CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
2977 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002978 QualType DeducedA) {
2979 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002980
Richard Smithb1efc9b2017-08-30 00:44:08 +00002981 auto Failed = [&]() -> Sema::TemplateDeductionResult {
2982 Info.FirstArg = TemplateArgument(DeducedA);
2983 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2984 Info.CallArgIndex = OriginalArg.ArgIdx;
2985 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
2986 : Sema::TDK_DeducedMismatch;
2987 };
2988
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002989 QualType A = OriginalArg.OriginalArgType;
2990 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002991
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002992 // Check for type equality (top-level cv-qualifiers are ignored).
2993 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00002994 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002995
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002996 // Strip off references on the argument types; they aren't needed for
2997 // the following checks.
2998 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2999 DeducedA = DeducedARef->getPointeeType();
3000 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3001 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003002
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003003 // C++ [temp.deduct.call]p4:
3004 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003005 // - If the original P is a reference type, the deduced A (i.e., the
3006 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003007 // the transformed A.
3008 if (const ReferenceType *OriginalParamRef
3009 = OriginalParamType->getAs<ReferenceType>()) {
3010 // We don't want to keep the reference around any more.
3011 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003012
Richard Smith1be59c52016-10-22 01:32:19 +00003013 // FIXME: Resolve core issue (no number yet): if the original P is a
3014 // reference type and the transformed A is function type "noexcept F",
3015 // the deduced A can be F.
3016 QualType Tmp;
3017 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003018 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00003019
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003020 Qualifiers AQuals = A.getQualifiers();
3021 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00003022
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003023 // Under Objective-C++ ARC, the deduced type may have implicitly
3024 // been given strong or (when dealing with a const reference)
3025 // unsafe_unretained lifetime. If so, update the original
3026 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00003027 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003028 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3029 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3030 (DeducedAQuals.hasConst() &&
3031 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3032 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00003033 }
3034
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003035 if (AQuals == DeducedAQuals) {
3036 // Qualifiers match; there's nothing to do.
3037 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00003038 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003039 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003040 // Qualifiers are compatible, so have the argument type adopt the
3041 // deduced argument type's qualifiers as if we had performed the
3042 // qualification conversion.
3043 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3044 }
3045 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003046
3047 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00003048 // type that can be converted to the deduced A via a function pointer
3049 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00003050 //
Richard Smith1be59c52016-10-22 01:32:19 +00003051 // Also allow conversions which merely strip __attribute__((noreturn)) from
3052 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003053 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003054 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003055 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003056 (S.IsQualificationConversion(A, DeducedA, false,
3057 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003058 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003059 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003060
Simon Pilgrim728134c2016-08-12 11:43:57 +00003061 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003062 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003063 // [...] Likewise, if P is a pointer to a class of the form
3064 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003065 // derived class pointed to by the deduced A.
3066 if (const PointerType *OriginalParamPtr
3067 = OriginalParamType->getAs<PointerType>()) {
3068 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3069 if (const PointerType *APtr = A->getAs<PointerType>()) {
3070 if (A->getPointeeType()->isRecordType()) {
3071 OriginalParamType = OriginalParamPtr->getPointeeType();
3072 DeducedA = DeducedAPtr->getPointeeType();
3073 A = APtr->getPointeeType();
3074 }
3075 }
3076 }
3077 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003078
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003079 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003080 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003081
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003082 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003083 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003084 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003085
Richard Smithb1efc9b2017-08-30 00:44:08 +00003086 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003087}
3088
Richard Smithc92d2062017-01-05 23:02:44 +00003089/// Find the pack index for a particular parameter index in an instantiation of
3090/// a function template with specific arguments.
3091///
3092/// \return The pack index for whichever pack produced this parameter, or -1
3093/// if this was not produced by a parameter. Intended to be used as the
3094/// ArgumentPackSubstitutionIndex for further substitutions.
3095// FIXME: We should track this in OriginalCallArgs so we don't need to
3096// reconstruct it here.
3097static unsigned getPackIndexForParam(Sema &S,
3098 FunctionTemplateDecl *FunctionTemplate,
3099 const MultiLevelTemplateArgumentList &Args,
3100 unsigned ParamIdx) {
3101 unsigned Idx = 0;
3102 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3103 if (PD->isParameterPack()) {
3104 unsigned NumExpansions =
3105 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3106 if (Idx + NumExpansions > ParamIdx)
3107 return ParamIdx - Idx;
3108 Idx += NumExpansions;
3109 } else {
3110 if (Idx == ParamIdx)
3111 return -1; // Not a pack expansion
3112 ++Idx;
3113 }
3114 }
3115
3116 llvm_unreachable("parameter index would not be produced from template");
3117}
3118
Mike Stump11289f42009-09-09 15:08:12 +00003119/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003120/// checking the deduced template arguments for completeness and forming
3121/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003122///
3123/// \param OriginalCallArgs If non-NULL, the original call arguments against
3124/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003125Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3126 FunctionTemplateDecl *FunctionTemplate,
3127 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3128 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3129 TemplateDeductionInfo &Info,
3130 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3131 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003132 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003133 EnterExpressionEvaluationContext Unevaluated(
3134 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003135 SFINAETrap Trap(*this);
3136
Douglas Gregor9b146582009-07-08 20:55:45 +00003137 // Enter a new template instantiation context while we instantiate the
3138 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003139 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003140 InstantiatingTemplate Inst(
3141 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3142 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003143 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003144 return TDK_InstantiationDepth;
3145
John McCalle23b8712010-04-29 01:18:58 +00003146 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003147
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003148 // C++ [temp.deduct.type]p2:
3149 // [...] or if any template argument remains neither deduced nor
3150 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003152 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003153 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003154 CurrentInstantiationScope, NumExplicitlySpecified,
3155 PartialOverloading))
3156 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003157
Richard Smith6eedfe72017-01-09 08:01:21 +00003158 // C++ [temp.deduct.call]p10: [DR1391]
3159 // If deduction succeeds for all parameters that contain
3160 // template-parameters that participate in template argument deduction,
3161 // and all template arguments are explicitly specified, deduced, or
3162 // obtained from default template arguments, remaining parameters are then
3163 // compared with the corresponding arguments. For each remaining parameter
3164 // P with a type that was non-dependent before substitution of any
3165 // explicitly-specified template arguments, if the corresponding argument
3166 // A cannot be implicitly converted to P, deduction fails.
3167 if (CheckNonDependent())
3168 return TDK_NonDependentConversionFailure;
3169
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003170 // Form the template argument list from the deduced template arguments.
3171 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003172 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003173 Info.reset(DeducedArgumentList);
3174
Mike Stump11289f42009-09-09 15:08:12 +00003175 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003176 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003177 DeclContext *Owner = FunctionTemplate->getDeclContext();
3178 if (FunctionTemplate->getFriendObjectKind())
3179 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003180 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003181 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003182 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003183 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003184 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003185
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003186 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003187 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
Mike Stump11289f42009-09-09 15:08:12 +00003189 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003190 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003191 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3192 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003193 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003195 // There may have been an error that did not prevent us from constructing a
3196 // declaration. Mark the declaration invalid and return with a substitution
3197 // failure.
3198 if (Trap.hasErrorOccurred()) {
3199 Specialization->setInvalidDecl(true);
3200 return TDK_SubstitutionFailure;
3201 }
3202
Douglas Gregore65aacb2011-06-16 16:50:48 +00003203 if (OriginalCallArgs) {
3204 // C++ [temp.deduct.call]p4:
3205 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003206 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003207 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003208 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003209 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3210 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003211
Richard Smithc92d2062017-01-05 23:02:44 +00003212 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003213 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003214 // FIXME: This presumably means a pack ended up smaller than we
3215 // expected while deducing. Should this not result in deduction
3216 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003217 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003218
Richard Smithc92d2062017-01-05 23:02:44 +00003219 QualType DeducedA;
3220 if (!OriginalArg.DecomposedParam) {
3221 // P is one of the function parameters, just look up its substituted
3222 // type.
3223 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3224 } else {
3225 // P is a decomposed element of a parameter corresponding to a
3226 // braced-init-list argument. Substitute back into P to find the
3227 // deduced A.
3228 QualType &CacheEntry =
3229 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3230 if (CacheEntry.isNull()) {
3231 ArgumentPackSubstitutionIndexRAII PackIndex(
3232 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3233 ParamIdx));
3234 CacheEntry =
3235 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3236 Specialization->getTypeSpecStartLoc(),
3237 Specialization->getDeclName());
3238 }
3239 DeducedA = CacheEntry;
3240 }
3241
Richard Smithb1efc9b2017-08-30 00:44:08 +00003242 if (auto TDK =
3243 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3244 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003245 }
3246 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003247
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003248 // If we suppressed any diagnostics while performing template argument
3249 // deduction, and if we haven't already instantiated this declaration,
3250 // keep track of these diagnostics. They'll be emitted if this specialization
3251 // is actually used.
3252 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003253 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003254 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3255 if (Pos == SuppressedDiagnostics.end())
3256 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3257 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003259
Mike Stump11289f42009-09-09 15:08:12 +00003260 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003261}
3262
John McCall8d08b9b2010-08-27 09:08:28 +00003263/// Gets the type of a function for template-argument-deducton
3264/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003265static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003266 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003267 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003268 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003269 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003270 return QualType();
3271
John McCallc1f69982010-02-02 02:21:27 +00003272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003273 if (Method->isInstance()) {
3274 // An instance method that's referenced in a form that doesn't
3275 // look like a member pointer is just invalid.
3276 if (!R.HasFormOfMemberPointer) return QualType();
3277
Richard Smith2a7d4812013-05-04 07:00:32 +00003278 return S.Context.getMemberPointerType(Fn->getType(),
3279 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003280 }
3281
3282 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003283 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003284}
3285
3286/// Apply the deduction rules for overload sets.
3287///
3288/// \return the null type if this argument should be treated as an
3289/// undeduced context
3290static QualType
3291ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003292 Expr *Arg, QualType ParamType,
3293 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294
John McCall8d08b9b2010-08-27 09:08:28 +00003295 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003296
John McCall8d08b9b2010-08-27 09:08:28 +00003297 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003298
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003299 // C++0x [temp.deduct.call]p4
3300 unsigned TDF = 0;
3301 if (ParamWasReference)
3302 TDF |= TDF_ParamWithReferenceType;
3303 if (R.IsAddressOfOperand)
3304 TDF |= TDF_IgnoreQualifiers;
3305
John McCallc1f69982010-02-02 02:21:27 +00003306 // C++0x [temp.deduct.call]p6:
3307 // When P is a function type, pointer to function type, or pointer
3308 // to member function type:
3309
3310 if (!ParamType->isFunctionType() &&
3311 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003312 !ParamType->isMemberFunctionPointerType()) {
3313 if (Ovl->hasExplicitTemplateArgs()) {
3314 // But we can still look for an explicit specialization.
3315 if (FunctionDecl *ExplicitSpec
3316 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003317 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003318 }
John McCallc1f69982010-02-02 02:21:27 +00003319
George Burgess IVcc2f3552016-03-19 21:51:45 +00003320 DeclAccessPair DAP;
3321 if (FunctionDecl *Viable =
3322 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3323 return GetTypeOfFunction(S, R, Viable);
3324
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003325 return QualType();
3326 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003327
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003328 // Gather the explicit template arguments, if any.
3329 TemplateArgumentListInfo ExplicitTemplateArgs;
3330 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003331 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003332 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003333 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3334 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003335 NamedDecl *D = (*I)->getUnderlyingDecl();
3336
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003337 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3338 // - If the argument is an overload set containing one or more
3339 // function templates, the parameter is treated as a
3340 // non-deduced context.
3341 if (!Ovl->hasExplicitTemplateArgs())
3342 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003343
3344 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003345 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003346 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003347 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3348 Specialization, Info))
3349 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003350
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003351 D = Specialization;
3352 }
John McCallc1f69982010-02-02 02:21:27 +00003353
3354 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003355 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003356 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003357
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003358 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003360 ArgType->isFunctionType())
3361 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
John McCallc1f69982010-02-02 02:21:27 +00003363 // - If the argument is an overload set (not containing function
3364 // templates), trial argument deduction is attempted using each
3365 // of the members of the set. If deduction succeeds for only one
3366 // of the overload set members, that member is used as the
3367 // argument value for the deduction. If deduction succeeds for
3368 // more than one member of the overload set the parameter is
3369 // treated as a non-deduced context.
3370
3371 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3372 // Type deduction is done independently for each P/A pair, and
3373 // the deduced template argument values are then combined.
3374 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003375 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003376 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003377 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003378 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003379 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3380 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003381 if (Result) continue;
3382 if (!Match.isNull()) return QualType();
3383 Match = ArgType;
3384 }
3385
3386 return Match;
3387}
3388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003390/// described in C++ [temp.deduct.call].
3391///
3392/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003393/// argument deduction based on this P/A pair because the argument is an
3394/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003395static bool AdjustFunctionParmAndArgTypesForDeduction(
3396 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3397 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003398 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003399 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003400 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003401 if (ParamType.hasQualifiers())
3402 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003403
3404 // [...] If P is a reference type, the type referred to by P is
3405 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003406 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003407 if (ParamRefType)
3408 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003409
Nathan Sidwell96090022015-01-16 15:20:14 +00003410 // Overload sets usually make this parameter an undeduced context,
3411 // but there are sometimes special circumstances. Typically
3412 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003413 if (ArgType == S.Context.OverloadTy) {
3414 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3415 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003416 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 if (ArgType.isNull())
3418 return true;
3419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor7825bf32011-01-06 22:09:01 +00003421 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003422 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003423 if (ArgType->isIncompleteArrayType()) {
3424 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003425 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003426 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003427
Richard Smith32918772017-02-14 00:25:28 +00003428 // C++1z [temp.deduct.call]p3:
3429 // If P is a forwarding reference and the argument is an lvalue, the type
3430 // "lvalue reference to A" is used in place of A for type deduction.
3431 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003432 Arg->isLValue())
3433 ArgType = S.Context.getLValueReferenceType(ArgType);
3434 } else {
3435 // C++ [temp.deduct.call]p2:
3436 // If P is not a reference type:
3437 // - If A is an array type, the pointer type produced by the
3438 // array-to-pointer standard conversion (4.2) is used in place of
3439 // A for type deduction; otherwise,
3440 if (ArgType->isArrayType())
3441 ArgType = S.Context.getArrayDecayedType(ArgType);
3442 // - If A is a function type, the pointer type produced by the
3443 // function-to-pointer standard conversion (4.3) is used in place
3444 // of A for type deduction; otherwise,
3445 else if (ArgType->isFunctionType())
3446 ArgType = S.Context.getPointerType(ArgType);
3447 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003448 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003449 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003450 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003451 }
3452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453
Douglas Gregor7825bf32011-01-06 22:09:01 +00003454 // C++0x [temp.deduct.call]p4:
3455 // In general, the deduction process attempts to find template argument
3456 // values that will make the deduced A identical to A (after the type A
3457 // is transformed as described above). [...]
3458 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459
Douglas Gregor7825bf32011-01-06 22:09:01 +00003460 // - If the original P is a reference type, the deduced A (i.e., the
3461 // type referred to by the reference) can be more cv-qualified than
3462 // the transformed A.
3463 if (ParamRefType)
3464 TDF |= TDF_ParamWithReferenceType;
3465 // - The transformed A can be another pointer or pointer to member
3466 // type that can be converted to the deduced A via a qualification
3467 // conversion (4.4).
3468 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3469 ArgType->isObjCObjectPointerType())
3470 TDF |= TDF_IgnoreQualifiers;
3471 // - If P is a class and P has the form simple-template-id, then the
3472 // transformed A can be a derived class of the deduced A. Likewise,
3473 // if P is a pointer to a class of the form simple-template-id, the
3474 // transformed A can be a pointer to a derived class pointed to by
3475 // the deduced A.
3476 if (isSimpleTemplateIdType(ParamType) ||
3477 (isa<PointerType>(ParamType) &&
3478 isSimpleTemplateIdType(
3479 ParamType->getAs<PointerType>()->getPointeeType())))
3480 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481
Douglas Gregor7825bf32011-01-06 22:09:01 +00003482 return false;
3483}
3484
Richard Smithf0393bf2017-02-16 04:22:56 +00003485static bool
3486hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3487 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003488
Richard Smith707eab62017-01-05 04:08:31 +00003489static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003490 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3491 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003492 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3493 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003494 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003495
3496/// \brief Attempt template argument deduction from an initializer list
3497/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003498static Sema::TemplateDeductionResult DeduceFromInitializerList(
3499 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3500 InitListExpr *ILE, TemplateDeductionInfo &Info,
3501 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003502 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3503 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003504 // C++ [temp.deduct.call]p1: (CWG 1591)
3505 // If removing references and cv-qualifiers from P gives
3506 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3507 // a non-empty initializer list, then deduction is performed instead for
3508 // each element of the initializer list, taking P0 as a function template
3509 // parameter type and the initializer element as its argument
3510 //
Richard Smith707eab62017-01-05 04:08:31 +00003511 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003512 if (!ILE->getNumInits())
3513 return Sema::TDK_Success;
3514
Richard Smitha7d5ec92017-01-04 19:47:19 +00003515 QualType ElTy;
3516 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3517 if (ArrTy)
3518 ElTy = ArrTy->getElementType();
3519 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3520 // Otherwise, an initializer list argument causes the parameter to be
3521 // considered a non-deduced context
3522 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003523 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003524
Faisal Valif6dfdb32015-12-10 05:36:39 +00003525 // Deduction only needs to be done for dependent types.
3526 if (ElTy->isDependentType()) {
3527 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003528 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003529 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003530 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003531 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003532 }
3533 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003534
3535 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3536 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003537 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003538 // Determine the array bound is something we can deduce.
3539 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003540 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003541 // We can perform template argument deduction for the given non-type
3542 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003543 // C++ [temp.deduct.type]p13:
3544 // The type of N in the type T[N] is std::size_t.
3545 QualType T = S.Context.getSizeType();
3546 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003547 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003548 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003549 /*ArrayBound=*/true, Info, Deduced))
3550 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003551 }
3552 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003553
3554 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003555}
3556
Richard Smith707eab62017-01-05 04:08:31 +00003557/// \brief Perform template argument deduction per [temp.deduct.call] for a
3558/// single parameter / argument pair.
3559static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003560 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3561 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003562 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3563 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003564 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003565 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003566 QualType OrigParamType = ParamType;
3567
3568 // If P is a reference type [...]
3569 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003570 if (AdjustFunctionParmAndArgTypesForDeduction(
3571 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003572 return Sema::TDK_Success;
3573
Richard Smith707eab62017-01-05 04:08:31 +00003574 // If [...] the argument is a non-empty initializer list [...]
3575 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3576 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003577 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003578
3579 // [...] the deduction process attempts to find template argument values
3580 // that will make the deduced A identical to A
3581 //
3582 // Keep track of the argument type and corresponding parameter index,
3583 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003584 OriginalCallArgs.push_back(
3585 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003586 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003587 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003588}
3589
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003590/// \brief Perform template argument deduction from a function call
3591/// (C++ [temp.deduct.call]).
3592///
3593/// \param FunctionTemplate the function template for which we are performing
3594/// template argument deduction.
3595///
James Dennett18348b62012-06-22 08:52:37 +00003596/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003597/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003598///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003599/// \param Args the function call arguments
3600///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003601/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003602/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003603/// template argument deduction.
3604///
3605/// \param Info the argument will be updated to provide additional information
3606/// about template argument deduction.
3607///
Richard Smith6eedfe72017-01-09 08:01:21 +00003608/// \param CheckNonDependent A callback to invoke to check conversions for
3609/// non-dependent parameters, between deduction and substitution, per DR1391.
3610/// If this returns true, substitution will be skipped and we return
3611/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3612/// types (after substituting explicit template arguments).
3613///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003614/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003615Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3616 FunctionTemplateDecl *FunctionTemplate,
3617 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003618 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003619 bool PartialOverloading,
3620 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003621 if (FunctionTemplate->isInvalidDecl())
3622 return TDK_Invalid;
3623
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003624 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003625 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003626
Richard Smith32918772017-02-14 00:25:28 +00003627 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3628
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003629 // C++ [temp.deduct.call]p1:
3630 // Template argument deduction is done by comparing each function template
3631 // parameter type (call it P) with the type of the corresponding argument
3632 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003633 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003634 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003635 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003636 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003637 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003638 if (Proto->isTemplateVariadic())
3639 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003640 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003641 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003642 }
Mike Stump11289f42009-09-09 15:08:12 +00003643
Douglas Gregor89026b52009-06-30 23:57:56 +00003644 // The types of the parameters from which we will perform template argument
3645 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003646 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003647 TemplateParameterList *TemplateParams
3648 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003649 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003650 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003651 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003652 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003653 TemplateDeductionResult Result =
3654 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003655 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003656 Deduced,
3657 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003658 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003659 Info);
3660 if (Result)
3661 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003662
3663 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003664 } else {
3665 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003666 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003667 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3668 }
Mike Stump11289f42009-09-09 15:08:12 +00003669
Richard Smith6eedfe72017-01-09 08:01:21 +00003670 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003671
3672 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3673 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003674 // C++ [demp.deduct.call]p1: (DR1391)
3675 // Template argument deduction is done by comparing each function template
3676 // parameter that contains template-parameters that participate in
3677 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003678 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003679 return Sema::TDK_Success;
3680
Richard Smith707eab62017-01-05 04:08:31 +00003681 // ... with the type of the corresponding argument
3682 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003683 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003684 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003685 };
3686
Douglas Gregor89026b52009-06-30 23:57:56 +00003687 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003688 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003689 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003690 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003691 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003692 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003693
Richard Smitha7d5ec92017-01-04 19:47:19 +00003694 const PackExpansionType *ParamExpansion =
3695 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003696 if (!ParamExpansion) {
3697 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003698 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003699 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Richard Smith6eedfe72017-01-09 08:01:21 +00003701 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003702 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003703 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregor7825bf32011-01-06 22:09:01 +00003705 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707
Richard Smithde0d34a2017-01-09 07:14:40 +00003708 QualType ParamPattern = ParamExpansion->getPattern();
3709 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3710 ParamPattern);
3711
Douglas Gregor7825bf32011-01-06 22:09:01 +00003712 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 // For a function parameter pack that occurs at the end of the
3714 // parameter-declaration-list, the type A of each remaining argument of
3715 // the call is compared with the type P of the declarator-id of the
3716 // function parameter pack. Each comparison deduces template arguments
3717 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003718 // the function parameter pack. When a function parameter pack appears
3719 // in a non-deduced context [not at the end of the list], the type of
3720 // that parameter pack is never deduced.
3721 //
3722 // FIXME: The above rule allows the size of the parameter pack to change
3723 // after we skip it (in the non-deduced case). That makes no sense, so
3724 // we instead notionally deduce the pack against N arguments, where N is
3725 // the length of the explicitly-specified pack if it's expanded by the
3726 // parameter pack and 0 otherwise, and we treat each deduction as a
3727 // non-deduced context.
3728 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003729 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3730 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003731 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3732 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003733 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003734 } else {
3735 // If the parameter type contains an explicitly-specified pack that we
3736 // could not expand, skip the number of parameters notionally created
3737 // by the expansion.
3738 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003739 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003740 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003741 ++I, ++ArgIdx) {
3742 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003743 // FIXME: Should we add OriginalCallArgs for these? What if the
3744 // corresponding argument is a list?
3745 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003746 }
3747 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Douglas Gregor7825bf32011-01-06 22:09:01 +00003750 // Build argument packs for each of the parameter packs expanded by this
3751 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003752 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003754 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003755
Richard Smith6eedfe72017-01-09 08:01:21 +00003756 return FinishTemplateArgumentDeduction(
3757 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3758 &OriginalCallArgs, PartialOverloading,
3759 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003760}
3761
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003762QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003763 QualType FunctionType,
3764 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003765 if (ArgFunctionType.isNull())
3766 return ArgFunctionType;
3767
3768 const FunctionProtoType *FunctionTypeP =
3769 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003770 const FunctionProtoType *ArgFunctionTypeP =
3771 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003772
3773 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3774 bool Rebuild = false;
3775
3776 CallingConv CC = FunctionTypeP->getCallConv();
3777 if (EPI.ExtInfo.getCC() != CC) {
3778 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3779 Rebuild = true;
3780 }
3781
3782 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3783 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3784 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3785 Rebuild = true;
3786 }
3787
3788 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3789 ArgFunctionTypeP->hasExceptionSpec())) {
3790 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3791 Rebuild = true;
3792 }
3793
3794 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003795 return ArgFunctionType;
3796
Richard Smithbaa47832016-12-01 02:11:49 +00003797 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3798 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003799}
3800
Douglas Gregor9b146582009-07-08 20:55:45 +00003801/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003802/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3803/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003804///
3805/// \param FunctionTemplate the function template for which we are performing
3806/// template argument deduction.
3807///
James Dennett18348b62012-06-22 08:52:37 +00003808/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003809/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003810///
3811/// \param ArgFunctionType the function type that will be used as the
3812/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003813/// function template's function type. This type may be NULL, if there is no
3814/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003815///
3816/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003817/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003818/// template argument deduction.
3819///
3820/// \param Info the argument will be updated to provide additional information
3821/// about template argument deduction.
3822///
Richard Smithbaa47832016-12-01 02:11:49 +00003823/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3824/// the address of a function template per [temp.deduct.funcaddr] and
3825/// [over.over]. If \c false, we are looking up a function template
3826/// specialization based on its signature, per [temp.deduct.decl].
3827///
Douglas Gregor9b146582009-07-08 20:55:45 +00003828/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003829Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3830 FunctionTemplateDecl *FunctionTemplate,
3831 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3832 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3833 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003834 if (FunctionTemplate->isInvalidDecl())
3835 return TDK_Invalid;
3836
Douglas Gregor9b146582009-07-08 20:55:45 +00003837 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3838 TemplateParameterList *TemplateParams
3839 = FunctionTemplate->getTemplateParameters();
3840 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003841
Douglas Gregor9b146582009-07-08 20:55:45 +00003842 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003843 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003844 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003845 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003846 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003847 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003848 if (TemplateDeductionResult Result
3849 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003850 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003851 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003852 &FunctionType, Info))
3853 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003854
3855 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003856 }
3857
Richard Smithcd198152017-06-07 21:46:22 +00003858 // When taking the address of a function, we require convertibility of
3859 // the resulting function type. Otherwise, we allow arbitrary mismatches
3860 // of calling convention and noreturn.
3861 if (!IsAddressOfFunction)
3862 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3863 /*AdjustExceptionSpec*/false);
3864
Eli Friedman77dcc722012-02-08 03:07:05 +00003865 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003866 EnterExpressionEvaluationContext Unevaluated(
3867 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003868 SFINAETrap Trap(*this);
3869
John McCallc1f69982010-02-02 02:21:27 +00003870 Deduced.resize(TemplateParams->size());
3871
Richard Smith2a7d4812013-05-04 07:00:32 +00003872 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003873 // type so that we treat it as a non-deduced context in what follows. If we
3874 // are looking up by signature, the signature type should also have a deduced
3875 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003876 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003877 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003878 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003879 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003880 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003881 }
3882
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003883 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00003884 unsigned TDF =
3885 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003886 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003887 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003888 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003889 FunctionType, ArgFunctionType,
3890 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003891 return Result;
3892 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003893
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003895 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3896 NumExplicitlySpecified,
3897 Specialization, Info))
3898 return Result;
3899
Richard Smith2a7d4812013-05-04 07:00:32 +00003900 // If the function has a deduced return type, deduce it now, so we can check
3901 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003902 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003903 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003904 DeduceReturnType(Specialization, Info.getLocation(), false))
3905 return TDK_MiscellaneousDeductionFailure;
3906
Richard Smith9095e5b2016-11-01 01:31:23 +00003907 // If the function has a dependent exception specification, resolve it now,
3908 // so we can check that the exception specification matches.
3909 auto *SpecializationFPT =
3910 Specialization->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003911 if (getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +00003912 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3913 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3914 return TDK_MiscellaneousDeductionFailure;
3915
Richard Smithcd198152017-06-07 21:46:22 +00003916 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00003917 // substituted and resolved type we just formed. (Calling convention and
3918 // noreturn can't be dependent, so we don't actually need this for them
3919 // right now.)
3920 QualType SpecializationType = Specialization->getType();
3921 if (!IsAddressOfFunction)
3922 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3923 /*AdjustExceptionSpec*/true);
3924
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003925 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003926 // specialization with respect to arguments of compatible pointer to function
3927 // types, template argument deduction fails.
3928 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003929 if (IsAddressOfFunction &&
3930 !isSameOrCompatibleFunctionType(
3931 Context.getCanonicalType(SpecializationType),
3932 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003933 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003934
3935 if (!IsAddressOfFunction &&
3936 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003937 return TDK_MiscellaneousDeductionFailure;
3938 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003939
3940 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003941}
3942
Simon Pilgrim728134c2016-08-12 11:43:57 +00003943/// \brief Given a function declaration (e.g. a generic lambda conversion
3944/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003945/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3946/// to replace 'auto' with and not the actual result type you want
3947/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003948static inline void
3949SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003950 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003951 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003952 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003953 assert(AutoResultType->getContainedAutoType());
3954 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003955 TypeToReplaceAutoWith);
3956 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3957}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003958
Simon Pilgrim728134c2016-08-12 11:43:57 +00003959/// \brief Given a specialized conversion operator of a generic lambda
3960/// create the corresponding specializations of the call operator and
3961/// the static-invoker. If the return type of the call operator is auto,
3962/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003963/// return type of the destination function ptr.
3964
Simon Pilgrim728134c2016-08-12 11:43:57 +00003965static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003966SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3967 CXXConversionDecl *ConversionSpecialized,
3968 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3969 QualType ReturnTypeOfDestFunctionPtr,
3970 TemplateDeductionInfo &TDInfo,
3971 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003972
Faisal Vali2b3a3012013-10-24 23:40:02 +00003973 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003974 assert(LambdaClass && LambdaClass->isGenericLambda());
3975
Faisal Vali2b3a3012013-10-24 23:40:02 +00003976 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003977 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003978 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003979 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003980
3981 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003982 CallOpGeneric->getDescribedFunctionTemplate();
3983
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003985 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003986 // generic lambda's call operator.
3987 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003988 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3989 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003990 0, CallOpSpecialized, TDInfo))
3991 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003992
Faisal Vali2b3a3012013-10-24 23:40:02 +00003993 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003994 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3995 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003996 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003997 CallOpSpecialized->getPointOfInstantiation(),
3998 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003999
Faisal Vali2b3a3012013-10-24 23:40:02 +00004000 // Check to see if the return type of the destination ptr-to-function
4001 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00004002 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00004003 ReturnTypeOfDestFunctionPtr))
4004 return Sema::TDK_NonDeducedMismatch;
4005 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00004006 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00004007 // specialized our corresponding call operator, we are ready to
4008 // specialize the static invoker with the deduced arguments of our
4009 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00004010 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00004011 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
4012 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
4013
Yaron Kerenf428fcf2015-05-13 17:56:46 +00004014#ifndef NDEBUG
4015 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
4016#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00004017 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004018 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00004019 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00004020 "If the call operator succeeded so should the invoker!");
4021 // Set the result type to match the corresponding call operator
4022 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00004023 if (GenericLambdaCallOperatorHasDeducedReturnType &&
4024 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00004025 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00004026 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00004027 // to substitute into the 'auto' of the invoker and conversion
4028 // function.
4029 // For e.g.
4030 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
4031 // We don't want to subst 'int*' into 'auto' to get int**.
4032
Alp Toker314cc812014-01-25 16:55:45 +00004033 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
4034 ->getContainedAutoType()
4035 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00004036 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
4037 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00004038 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004039 TypeToReplaceAutoWith, S);
4040 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00004041
Faisal Vali2b3a3012013-10-24 23:40:02 +00004042 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00004043 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00004044 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00004045 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00004046 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
4047 getType().getTypePtr()->castAs<FunctionProtoType>();
4048 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
4049 EPI.TypeQuals = 0;
4050 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00004051 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00004052 return Sema::TDK_Success;
4053}
Douglas Gregor05155d82009-08-21 23:19:43 +00004054/// \brief Deduce template arguments for a templated conversion
4055/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4056/// conversion function template specialization.
4057Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004058Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004059 QualType ToType,
4060 CXXConversionDecl *&Specialization,
4061 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004062 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004063 return TDK_Invalid;
4064
Faisal Vali2b3a3012013-10-24 23:40:02 +00004065 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004066 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4067
Faisal Vali2b3a3012013-10-24 23:40:02 +00004068 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004069
4070 // Canonicalize the types for deduction.
4071 QualType P = Context.getCanonicalType(FromType);
4072 QualType A = Context.getCanonicalType(ToType);
4073
Douglas Gregord99609a2011-03-06 09:03:20 +00004074 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004075 // If P is a reference type, the type referred to by P is used for
4076 // type deduction.
4077 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4078 P = PRef->getPointeeType();
4079
Douglas Gregord99609a2011-03-06 09:03:20 +00004080 // C++0x [temp.deduct.conv]p4:
4081 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004082 // for type deduction.
4083 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00004084 A = ARef->getPointeeType().getUnqualifiedType();
4085 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004086 //
Mike Stump11289f42009-09-09 15:08:12 +00004087 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00004088 else {
4089 assert(!A->isReferenceType() && "Reference types were handled above");
4090
4091 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004092 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004093 // of P for type deduction; otherwise,
4094 if (P->isArrayType())
4095 P = Context.getArrayDecayedType(P);
4096 // - If P is a function type, the pointer type produced by the
4097 // function-to-pointer standard conversion (4.3) is used in
4098 // place of P for type deduction; otherwise,
4099 else if (P->isFunctionType())
4100 P = Context.getPointerType(P);
4101 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004102 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004103 else
4104 P = P.getUnqualifiedType();
4105
Douglas Gregord99609a2011-03-06 09:03:20 +00004106 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004107 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004108 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004109 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004110 A = A.getUnqualifiedType();
4111 }
4112
Eli Friedman77dcc722012-02-08 03:07:05 +00004113 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004114 EnterExpressionEvaluationContext Unevaluated(
4115 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004116 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004117
4118 // C++ [temp.deduct.conv]p1:
4119 // Template argument deduction is done by comparing the return
4120 // type of the template conversion function (call it P) with the
4121 // type that is required as the result of the conversion (call it
4122 // A) as described in 14.8.2.4.
4123 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004124 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004125 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004126 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004127
4128 // C++0x [temp.deduct.conv]p4:
4129 // In general, the deduction process attempts to find template
4130 // argument values that will make the deduced A identical to
4131 // A. However, there are two cases that allow a difference:
4132 unsigned TDF = 0;
4133 // - If the original A is a reference type, A can be more
4134 // cv-qualified than the deduced A (i.e., the type referred to
4135 // by the reference)
4136 if (ToType->isReferenceType())
4137 TDF |= TDF_ParamWithReferenceType;
4138 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004139 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004140 // conversion.
4141 //
4142 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4143 // both P and A are pointers or member pointers. In this case, we
4144 // just ignore cv-qualifiers completely).
4145 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004146 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004147 TDF |= TDF_IgnoreQualifiers;
4148 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004149 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4150 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004151 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004152
4153 // Create an Instantiation Scope for finalizing the operator.
4154 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004155 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004156 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004157 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004158 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004159 ConversionSpecialized, Info);
4160 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4161
4162 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00004163 // to a ptr-to-function, use the deduced arguments from the conversion
4164 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00004165 // e.g., int (*fp)(int) = [](auto a) { return a; };
4166 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00004167
Faisal Vali2b3a3012013-10-24 23:40:02 +00004168 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00004169 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00004170 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00004171 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00004172 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00004173 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00004174 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00004175 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
4176
Simon Pilgrim728134c2016-08-12 11:43:57 +00004177 // Create the corresponding specializations of the call operator and
4178 // the static-invoker; and if the return type is auto,
4179 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00004180 // DestFunctionPtrReturnType.
4181 // For instance:
4182 // auto L = [](auto a) { return f(a); };
4183 // int (*fp)(int) = L;
4184 // char (*fp2)(int) = L; <-- Not OK.
4185
4186 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00004187 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004188 Info, *this);
4189 }
Douglas Gregor05155d82009-08-21 23:19:43 +00004190 return Result;
4191}
4192
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004193/// \brief Deduce template arguments for a function template when there is
4194/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4195///
4196/// \param FunctionTemplate the function template for which we are performing
4197/// template argument deduction.
4198///
James Dennett18348b62012-06-22 08:52:37 +00004199/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004200/// arguments.
4201///
4202/// \param Specialization if template argument deduction was successful,
4203/// this will be set to the function template specialization produced by
4204/// template argument deduction.
4205///
4206/// \param Info the argument will be updated to provide additional information
4207/// about template argument deduction.
4208///
Richard Smithbaa47832016-12-01 02:11:49 +00004209/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4210/// the address of a function template in a context where we do not have a
4211/// target type, per [over.over]. If \c false, we are looking up a function
4212/// template specialization based on its signature, which only happens when
4213/// deducing a function parameter type from an argument that is a template-id
4214/// naming a function template specialization.
4215///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004216/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004217Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4218 FunctionTemplateDecl *FunctionTemplate,
4219 TemplateArgumentListInfo *ExplicitTemplateArgs,
4220 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4221 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004222 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004223 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004224 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004225}
4226
Richard Smith30482bc2011-02-20 03:19:35 +00004227namespace {
Richard Smith60437622017-02-09 19:17:44 +00004228 /// Substitute the 'auto' specifier or deduced template specialization type
4229 /// specifier within a type for a given replacement type.
4230 class SubstituteDeducedTypeTransform :
4231 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004232 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004233 bool UseTypeSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004234 public:
Richard Smith60437622017-02-09 19:17:44 +00004235 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4236 bool UseTypeSugar = true)
4237 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4238 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4239
4240 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4241 assert(isa<TemplateTypeParmType>(Replacement) &&
4242 "unexpected unsugared replacement kind");
4243 QualType Result = Replacement;
4244 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4245 NewTL.setNameLoc(TL.getNameLoc());
4246 return Result;
4247 }
Nico Weberc153d242014-07-28 00:02:09 +00004248
Richard Smith30482bc2011-02-20 03:19:35 +00004249 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4250 // If we're building the type pattern to deduce against, don't wrap the
4251 // substituted type in an AutoType. Certain template deduction rules
4252 // apply only when a template type parameter appears directly (and not if
4253 // the parameter is found through desugaring). For instance:
4254 // auto &&lref = lvalue;
4255 // must transform into "rvalue reference to T" not "rvalue reference to
4256 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004257 //
4258 // FIXME: Is this still necessary?
4259 if (!UseTypeSugar)
4260 return TransformDesugared(TLB, TL);
4261
4262 QualType Result = SemaRef.Context.getAutoType(
4263 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4264 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4265 NewTL.setNameLoc(TL.getNameLoc());
4266 return Result;
4267 }
4268
4269 QualType TransformDeducedTemplateSpecializationType(
4270 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4271 if (!UseTypeSugar)
4272 return TransformDesugared(TLB, TL);
4273
4274 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4275 TL.getTypePtr()->getTemplateName(),
4276 Replacement, Replacement.isNull());
4277 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4278 NewTL.setNameLoc(TL.getNameLoc());
4279 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004280 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004281
4282 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4283 // Lambdas never need to be transformed.
4284 return E;
4285 }
Richard Smith061f1e22013-04-30 21:23:01 +00004286
Richard Smith2a7d4812013-05-04 07:00:32 +00004287 QualType Apply(TypeLoc TL) {
4288 // Create some scratch storage for the transformed type locations.
4289 // FIXME: We're just going to throw this information away. Don't build it.
4290 TypeLocBuilder TLB;
4291 TLB.reserve(TL.getFullDataSize());
4292 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004293 }
Richard Smith30482bc2011-02-20 03:19:35 +00004294 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004295}
Richard Smith30482bc2011-02-20 03:19:35 +00004296
Richard Smith2a7d4812013-05-04 07:00:32 +00004297Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004298Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4299 Optional<unsigned> DependentDeductionDepth) {
4300 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4301 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004302}
4303
Richard Smithb1efc9b2017-08-30 00:44:08 +00004304/// Attempt to produce an informative diagostic explaining why auto deduction
4305/// failed.
4306/// \return \c true if diagnosed, \c false if not.
4307static bool diagnoseAutoDeductionFailure(Sema &S,
4308 Sema::TemplateDeductionResult TDK,
4309 TemplateDeductionInfo &Info,
4310 ArrayRef<SourceRange> Ranges) {
4311 switch (TDK) {
4312 case Sema::TDK_Inconsistent: {
4313 // Inconsistent deduction means we were deducing from an initializer list.
4314 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4315 D << Info.FirstArg << Info.SecondArg;
4316 for (auto R : Ranges)
4317 D << R;
4318 return true;
4319 }
4320
4321 // FIXME: Are there other cases for which a custom diagnostic is more useful
4322 // than the basic "types don't match" diagnostic?
4323
4324 default:
4325 return false;
4326 }
4327}
4328
Richard Smith061f1e22013-04-30 21:23:01 +00004329/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004330///
Richard Smith87d263e2016-12-25 08:05:23 +00004331/// Note that this is done even if the initializer is dependent. (This is
4332/// necessary to support partial ordering of templates using 'auto'.)
4333/// A dependent type will be produced when deducing from a dependent type.
4334///
Richard Smith30482bc2011-02-20 03:19:35 +00004335/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004336/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004337/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004338/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004339/// \param DependentDeductionDepth Set if we should permit deduction in
4340/// dependent cases. This is necessary for template partial ordering with
4341/// 'auto' template parameters. The value specified is the template
4342/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004343Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004344Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4345 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004346 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004347 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4348 if (NonPlaceholder.isInvalid())
4349 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004350 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004351 }
4352
Richard Smith87d263e2016-12-25 08:05:23 +00004353 if (!DependentDeductionDepth &&
4354 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004355 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004356 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004357 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004358 }
4359
Richard Smith87d263e2016-12-25 08:05:23 +00004360 // Find the depth of template parameter to synthesize.
4361 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4362
Richard Smith74aeef52013-04-26 16:15:35 +00004363 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4364 // Since 'decltype(auto)' can only occur at the top of the type, we
4365 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004366 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004367 if (AT->isDecltypeAuto()) {
4368 if (isa<InitListExpr>(Init)) {
4369 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4370 return DAR_FailedAlreadyDiagnosed;
4371 }
4372
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004373 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004374 if (Deduced.isNull())
4375 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004376 // FIXME: Support a non-canonical deduced type for 'auto'.
4377 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004378 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004379 if (Result.isNull())
4380 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004381 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004382 } else if (!getLangOpts().CPlusPlus) {
4383 if (isa<InitListExpr>(Init)) {
4384 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4385 return DAR_FailedAlreadyDiagnosed;
4386 }
Richard Smith74aeef52013-04-26 16:15:35 +00004387 }
4388 }
4389
Richard Smith30482bc2011-02-20 03:19:35 +00004390 SourceLocation Loc = Init->getExprLoc();
4391
4392 LocalInstantiationScope InstScope(*this);
4393
4394 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004395 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4396 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004397 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4398 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004399 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4400 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004401
Richard Smith87d263e2016-12-25 08:05:23 +00004402 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004403 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004404 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004405 assert(!FuncParam.isNull() &&
4406 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004407
4408 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004409 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004410 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004411
Richard Smith87d263e2016-12-25 08:05:23 +00004412 TemplateDeductionInfo Info(Loc, Depth);
4413
4414 // If deduction failed, don't diagnose if the initializer is dependent; it
4415 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004416 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4417 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004418 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004419 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004420 assert(!Result.isNull() && "substituting DependentTy can't fail");
4421 return DAR_Succeeded;
4422 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004423 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4424 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004425 return DAR_Failed;
4426 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004427
Richard Smith707eab62017-01-05 04:08:31 +00004428 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4429
Richard Smith74801c82012-07-08 04:13:07 +00004430 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004431 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004432 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4433 // against that. Such deduction only succeeds if removing cv-qualifiers and
4434 // references results in std::initializer_list<T>.
4435 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4436 return DAR_Failed;
4437
Richard Smithb1efc9b2017-08-30 00:44:08 +00004438 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004439 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004440 Expr *Init = InitList->getInit(i);
4441
4442 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4443 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004444 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4445 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004446 return DeductionFailed(TDK, {DeducedFromInitRange,
4447 Init->getSourceRange()});
4448
4449 if (DeducedFromInitRange.isInvalid() &&
4450 Deduced[0].getKind() != TemplateArgument::Null)
4451 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004452 }
4453 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004454 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4455 Diag(Loc, diag::err_auto_bitfield);
4456 return DAR_FailedAlreadyDiagnosed;
4457 }
4458
Richard Smithb1efc9b2017-08-30 00:44:08 +00004459 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004460 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004461 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004462 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004463 }
Richard Smith30482bc2011-02-20 03:19:35 +00004464
Richard Smith87d263e2016-12-25 08:05:23 +00004465 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004466 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004467 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004468
Eli Friedmane4310952012-11-06 23:56:42 +00004469 QualType DeducedType = Deduced[0].getAsType();
4470
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004471 if (InitList) {
4472 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4473 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004474 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004475 }
4476
Richard Smith60437622017-02-09 19:17:44 +00004477 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004478 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004479 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004480
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004481 // Check that the deduced argument type is compatible with the original
4482 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004483 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004484 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004485 assert((bool)InitList == OriginalArg.DecomposedParam &&
4486 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004487 if (auto TDK =
4488 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004489 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004490 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004491 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004492 }
4493
Sebastian Redl09edce02012-01-23 22:09:39 +00004494 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004495}
4496
Simon Pilgrim728134c2016-08-12 11:43:57 +00004497QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004498 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004499 if (TypeToReplaceAuto->isDependentType())
4500 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004501 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004502 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004503}
4504
Richard Smith60437622017-02-09 19:17:44 +00004505TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4506 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004507 if (TypeToReplaceAuto->isDependentType())
4508 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004509 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004510 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004511}
4512
Richard Smith33c33c32017-02-04 01:28:01 +00004513QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4514 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004515 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4516 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004517 .TransformType(TypeWithAuto);
4518}
4519
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004520void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4521 if (isa<InitListExpr>(Init))
4522 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004523 VDecl->isInitCapture()
4524 ? diag::err_init_capture_deduction_failure_from_init_list
4525 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004526 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4527 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004528 Diag(VDecl->getLocation(),
4529 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4530 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004531 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4532 << Init->getSourceRange();
4533}
4534
Richard Smith2a7d4812013-05-04 07:00:32 +00004535bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4536 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004537 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004538
4539 if (FD->getTemplateInstantiationPattern())
4540 InstantiateFunctionDefinition(Loc, FD);
4541
Alp Toker314cc812014-01-25 16:55:45 +00004542 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004543 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4544 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4545 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4546 }
4547
4548 return StillUndeduced;
4549}
4550
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004552static void
4553AddImplicitObjectParameterType(ASTContext &Context,
4554 CXXMethodDecl *Method,
4555 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004556 // C++11 [temp.func.order]p3:
4557 // [...] The new parameter is of type "reference to cv A," where cv are
4558 // the cv-qualifiers of the function template (if any) and A is
4559 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004560 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004561 // The standard doesn't say explicitly, but we pick the appropriate kind of
4562 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004563 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4564 ArgTy = Context.getQualifiedType(ArgTy,
4565 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004566 if (Method->getRefQualifier() == RQ_RValue)
4567 ArgTy = Context.getRValueReferenceType(ArgTy);
4568 else
4569 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004570 ArgTypes.push_back(ArgTy);
4571}
4572
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004573/// \brief Determine whether the function template \p FT1 is at least as
4574/// specialized as \p FT2.
4575static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004576 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004577 FunctionTemplateDecl *FT1,
4578 FunctionTemplateDecl *FT2,
4579 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004580 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004581 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004583 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4584 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004586 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4587 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004588 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004589 Deduced.resize(TemplateParams->size());
4590
4591 // C++0x [temp.deduct.partial]p3:
4592 // The types used to determine the ordering depend on the context in which
4593 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004594 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004595 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004596 switch (TPOC) {
4597 case TPOC_Call: {
4598 // - In the context of a function call, the function parameter types are
4599 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004600 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4601 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004602
Eli Friedman3b5774a2012-09-19 23:27:04 +00004603 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004604 // [...] If only one of the function templates is a non-static
4605 // member, that function template is considered to have a new
4606 // first parameter inserted in its function parameter list. The
4607 // new parameter is of type "reference to cv A," where cv are
4608 // the cv-qualifiers of the function template (if any) and A is
4609 // the class of which the function template is a member.
4610 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004611 // Note that we interpret this to mean "if one of the function
4612 // templates is a non-static member and the other is a non-member";
4613 // otherwise, the ordering rules for static functions against non-static
4614 // functions don't make any sense.
4615 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004616 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4617 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004618 SmallVector<QualType, 4> Args1;
4619
Richard Smithe5b52202013-09-11 00:52:39 +00004620 unsigned NumComparedArguments = NumCallArguments1;
4621
4622 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004623 // Compare 'this' from Method1 against first parameter from Method2.
4624 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4625 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004626 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004627 // Compare 'this' from Method2 against first parameter from Method1.
4628 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004629 }
4630
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004631 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004632 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004633 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004634 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregorb837ea42011-01-11 17:34:58 +00004636 // C++ [temp.func.order]p5:
4637 // The presence of unused ellipsis and default arguments has no effect on
4638 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004639 if (Args1.size() > NumComparedArguments)
4640 Args1.resize(NumComparedArguments);
4641 if (Args2.size() > NumComparedArguments)
4642 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004643 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4644 Args1.data(), Args1.size(), Info, Deduced,
4645 TDF_None, /*PartialOrdering=*/true))
4646 return false;
4647
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004648 break;
4649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004651 case TPOC_Conversion:
4652 // - In the context of a call to a conversion operator, the return types
4653 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004654 if (DeduceTemplateArgumentsByTypeMatch(
4655 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4656 Info, Deduced, TDF_None,
4657 /*PartialOrdering=*/true))
4658 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004659 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004661 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004662 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004663 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004664 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4665 FD2->getType(), FD1->getType(),
4666 Info, Deduced, TDF_None,
4667 /*PartialOrdering=*/true))
4668 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004669 break;
4670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004672 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004673 // In most cases, all template parameters must have values in order for
4674 // deduction to succeed, but for partial ordering purposes a template
4675 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004676 // types being used for partial ordering. [ Note: a template parameter used
4677 // in a non-deduced context is considered used. -end note]
4678 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4679 for (; ArgIdx != NumArgs; ++ArgIdx)
4680 if (Deduced[ArgIdx].isNull())
4681 break;
4682
Richard Smithf0393bf2017-02-16 04:22:56 +00004683 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4684 // to substitute the deduced arguments back into the template and check that
4685 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004686
Richard Smithf0393bf2017-02-16 04:22:56 +00004687 if (ArgIdx == NumArgs) {
4688 // All template arguments were deduced. FT1 is at least as specialized
4689 // as FT2.
4690 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004691 }
4692
Richard Smithf0393bf2017-02-16 04:22:56 +00004693 // Figure out which template parameters were used.
4694 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4695 switch (TPOC) {
4696 case TPOC_Call:
4697 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4698 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4699 TemplateParams->getDepth(),
4700 UsedParameters);
4701 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Richard Smithf0393bf2017-02-16 04:22:56 +00004703 case TPOC_Conversion:
4704 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4705 TemplateParams->getDepth(), UsedParameters);
4706 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Richard Smithf0393bf2017-02-16 04:22:56 +00004708 case TPOC_Other:
4709 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4710 TemplateParams->getDepth(),
4711 UsedParameters);
4712 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004713 }
4714
Richard Smithf0393bf2017-02-16 04:22:56 +00004715 for (; ArgIdx != NumArgs; ++ArgIdx)
4716 // If this argument had no value deduced but was used in one of the types
4717 // used for partial ordering, then deduction fails.
4718 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4719 return false;
4720
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004721 return true;
4722}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Douglas Gregorcef1a032011-01-16 16:03:23 +00004724/// \brief Determine whether this a function template whose parameter-type-list
4725/// ends with a function parameter pack.
4726static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4727 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4728 unsigned NumParams = Function->getNumParams();
4729 if (NumParams == 0)
4730 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
Douglas Gregorcef1a032011-01-16 16:03:23 +00004732 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4733 if (!Last->isParameterPack())
4734 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregorcef1a032011-01-16 16:03:23 +00004736 // Make sure that no previous parameter is a parameter pack.
4737 while (--NumParams > 0) {
4738 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4739 return false;
4740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
Douglas Gregorcef1a032011-01-16 16:03:23 +00004742 return true;
4743}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Douglas Gregorbe999392009-09-15 16:23:51 +00004745/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004746/// to the rules of function template partial ordering (C++ [temp.func.order]).
4747///
4748/// \param FT1 the first function template
4749///
4750/// \param FT2 the second function template
4751///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004752/// \param TPOC the context in which we are performing partial ordering of
4753/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004754///
Richard Smithe5b52202013-09-11 00:52:39 +00004755/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4756/// only when \c TPOC is \c TPOC_Call.
4757///
4758/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4759/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004760///
Douglas Gregorbe999392009-09-15 16:23:51 +00004761/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004762/// template is more specialized, returns NULL.
4763FunctionTemplateDecl *
4764Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4765 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004766 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004767 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004768 unsigned NumCallArguments1,
4769 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004771 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004773 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004774
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004775 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004776 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004778 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004779 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004780
Douglas Gregorcef1a032011-01-16 16:03:23 +00004781 // FIXME: This mimics what GCC implements, but doesn't match up with the
4782 // proposed resolution for core issue 692. This area needs to be sorted out,
4783 // but for now we attempt to maintain compatibility.
4784 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4785 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4786 if (Variadic1 != Variadic2)
4787 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004788
Craig Topperc3ec1492014-05-26 06:22:03 +00004789 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004790}
Douglas Gregor9b146582009-07-08 20:55:45 +00004791
Douglas Gregor450f00842009-09-25 18:43:00 +00004792/// \brief Determine if the two templates are equivalent.
4793static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4794 if (T1 == T2)
4795 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
Douglas Gregor450f00842009-09-25 18:43:00 +00004797 if (!T1 || !T2)
4798 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799
Douglas Gregor450f00842009-09-25 18:43:00 +00004800 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4801}
4802
4803/// \brief Retrieve the most specialized of the given function template
4804/// specializations.
4805///
John McCall58cc69d2010-01-27 01:50:18 +00004806/// \param SpecBegin the start iterator of the function template
4807/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004808///
John McCall58cc69d2010-01-27 01:50:18 +00004809/// \param SpecEnd the end iterator of the function template
4810/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004811///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004813/// diagnostic should occur.
4814///
4815/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4816/// no matching candidates.
4817///
4818/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4819/// occurs.
4820///
4821/// \param CandidateDiag partial diagnostic used for each function template
4822/// specialization that is a candidate in the ambiguous ordering. One parameter
4823/// in this diagnostic should be unbound, which will correspond to the string
4824/// describing the template arguments for the function template specialization.
4825///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004827/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004828UnresolvedSetIterator Sema::getMostSpecialized(
4829 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4830 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004831 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4832 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4833 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004834 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004835 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004836 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004837 FailedCandidates.NoteCandidates(*this, Loc);
4838 }
John McCall58cc69d2010-01-27 01:50:18 +00004839 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
4842 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004843 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
Douglas Gregor450f00842009-09-25 18:43:00 +00004845 // Find the function template that is better than all of the templates it
4846 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004847 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004849 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004850 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004851 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4852 FunctionTemplateDecl *Challenger
4853 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004854 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004855 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004856 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004857 Challenger)) {
4858 Best = I;
4859 BestTemplate = Challenger;
4860 }
4861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Douglas Gregor450f00842009-09-25 18:43:00 +00004863 // Make sure that the "best" function template is more specialized than all
4864 // of the others.
4865 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004866 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4867 FunctionTemplateDecl *Challenger
4868 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004869 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004870 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004871 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004872 BestTemplate)) {
4873 Ambiguous = true;
4874 break;
4875 }
4876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877
Douglas Gregor450f00842009-09-25 18:43:00 +00004878 if (!Ambiguous) {
4879 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004880 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
Douglas Gregor450f00842009-09-25 18:43:00 +00004883 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004884 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004885 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Richard Smithb875c432013-05-04 01:51:08 +00004887 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004888 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4889 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004890 const auto *FD = cast<FunctionDecl>(*I);
4891 PD << FD << getTemplateArgumentBindingsText(
4892 FD->getPrimaryTemplate()->getTemplateParameters(),
4893 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004894 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004895 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004896 Diag((*I)->getLocation(), PD);
4897 }
Richard Smithb875c432013-05-04 01:51:08 +00004898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
John McCall58cc69d2010-01-27 01:50:18 +00004900 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004901}
4902
Richard Smith0da6dc42016-12-24 16:40:51 +00004903/// Determine whether one partial specialization, P1, is at least as
4904/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004905///
Richard Smith26b86ea2016-12-31 21:41:23 +00004906/// \tparam TemplateLikeDecl The kind of P2, which must be a
4907/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004908/// \param T1 The injected-class-name of P1 (faked for a variable template).
4909/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004910template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004911static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004912 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004913 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004914 // C++ [temp.class.order]p1:
4915 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916 // specialized as the second if, given the following rewrite to two
4917 // function templates, the first function template is at least as
4918 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004919 // templates (14.6.6.2):
4920 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921 // first partial specialization and has a single function parameter
4922 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004923 // arguments of the first partial specialization, and
4924 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925 // second partial specialization and has a single function parameter
4926 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004927 // arguments of the second partial specialization.
4928 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004929 // Rather than synthesize function templates, we merely perform the
4930 // equivalent partial ordering by performing deduction directly on
4931 // the template arguments of the class template partial
4932 // specializations. This computation is slightly simpler than the
4933 // general problem of function template partial ordering, because
4934 // class template partial specializations are more constrained. We
4935 // know that every template parameter is deducible from the class
4936 // template partial specialization's template arguments, for
4937 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004938 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004939
Richard Smith0da6dc42016-12-24 16:40:51 +00004940 // Determine whether P1 is at least as specialized as P2.
4941 Deduced.resize(P2->getTemplateParameters()->size());
4942 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4943 T2, T1, Info, Deduced, TDF_None,
4944 /*PartialOrdering=*/true))
4945 return false;
4946
4947 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4948 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004949 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4950 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004951 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4952 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004953 S, P2, /*PartialOrdering=*/true,
4954 TemplateArgumentList(TemplateArgumentList::OnStack,
4955 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004956 Deduced, Info))
4957 return false;
4958
4959 return true;
4960}
4961
4962/// \brief Returns the more specialized class template partial specialization
4963/// according to the rules of partial ordering of class template partial
4964/// specializations (C++ [temp.class.order]).
4965///
4966/// \param PS1 the first class template partial specialization
4967///
4968/// \param PS2 the second class template partial specialization
4969///
4970/// \returns the more specialized class template partial specialization. If
4971/// neither partial specialization is more specialized, returns NULL.
4972ClassTemplatePartialSpecializationDecl *
4973Sema::getMoreSpecializedPartialSpecialization(
4974 ClassTemplatePartialSpecializationDecl *PS1,
4975 ClassTemplatePartialSpecializationDecl *PS2,
4976 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004977 QualType PT1 = PS1->getInjectedSpecializationType();
4978 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Richard Smith0e617ec2016-12-27 07:56:27 +00004980 TemplateDeductionInfo Info(Loc);
4981 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4982 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004983
4984 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004985 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004986
4987 return Better1 ? PS1 : PS2;
4988}
4989
Richard Smith0e617ec2016-12-27 07:56:27 +00004990bool Sema::isMoreSpecializedThanPrimary(
4991 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4992 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4993 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4994 QualType PartialT = Spec->getInjectedSpecializationType();
4995 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4996 return false;
4997 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4998 Info.clearSFINAEDiagnostic();
4999 return false;
5000 }
5001 return true;
5002}
5003
Larisse Voufo39a1e502013-08-06 01:03:05 +00005004VarTemplatePartialSpecializationDecl *
5005Sema::getMoreSpecializedPartialSpecialization(
5006 VarTemplatePartialSpecializationDecl *PS1,
5007 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00005008 // Pretend the variable template specializations are class template
5009 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00005010 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00005011 "the partial specializations being compared should specialize"
5012 " the same template.");
5013 TemplateName Name(PS1->getSpecializedTemplate());
5014 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5015 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005016 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005017 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005018 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005019
Richard Smith0e617ec2016-12-27 07:56:27 +00005020 TemplateDeductionInfo Info(Loc);
5021 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5022 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023
Douglas Gregorbe999392009-09-15 16:23:51 +00005024 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005025 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026
Richard Smith0da6dc42016-12-24 16:40:51 +00005027 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00005028}
5029
Richard Smith0e617ec2016-12-27 07:56:27 +00005030bool Sema::isMoreSpecializedThanPrimary(
5031 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5032 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5033 // FIXME: Cache the injected template arguments rather than recomputing
5034 // them for each partial specialization.
5035 SmallVector<TemplateArgument, 8> PrimaryArgs;
5036 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5037 PrimaryArgs);
5038
5039 TemplateName CanonTemplate =
5040 Context.getCanonicalTemplateName(TemplateName(Primary));
5041 QualType PrimaryT = Context.getTemplateSpecializationType(
5042 CanonTemplate, PrimaryArgs);
5043 QualType PartialT = Context.getTemplateSpecializationType(
5044 CanonTemplate, Spec->getTemplateArgs().asArray());
5045 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5046 return false;
5047 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5048 Info.clearSFINAEDiagnostic();
5049 return false;
5050 }
5051 return true;
5052}
5053
Richard Smith26b86ea2016-12-31 21:41:23 +00005054bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5055 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5056 // C++1z [temp.arg.template]p4: (DR 150)
5057 // A template template-parameter P is at least as specialized as a
5058 // template template-argument A if, given the following rewrite to two
5059 // function templates...
5060
5061 // Rather than synthesize function templates, we merely perform the
5062 // equivalent partial ordering by performing deduction directly on
5063 // the template parameter lists of the template template parameters.
5064 //
5065 // Given an invented class template X with the template parameter list of
5066 // A (including default arguments):
5067 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5068 TemplateParameterList *A = AArg->getTemplateParameters();
5069
5070 // - Each function template has a single function parameter whose type is
5071 // a specialization of X with template arguments corresponding to the
5072 // template parameters from the respective function template
5073 SmallVector<TemplateArgument, 8> AArgs;
5074 Context.getInjectedTemplateArgs(A, AArgs);
5075
5076 // Check P's arguments against A's parameter list. This will fill in default
5077 // template arguments as needed. AArgs are already correct by construction.
5078 // We can't just use CheckTemplateIdType because that will expand alias
5079 // templates.
5080 SmallVector<TemplateArgument, 4> PArgs;
5081 {
5082 SFINAETrap Trap(*this);
5083
5084 Context.getInjectedTemplateArgs(P, PArgs);
5085 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5086 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5087 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5088 // expansions, to form an "as written" argument list.
5089 TemplateArgument Arg = PArgs[I];
5090 if (Arg.getKind() == TemplateArgument::Pack) {
5091 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5092 Arg = *Arg.pack_begin();
5093 }
5094 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5095 Arg, QualType(), P->getParam(I)->getLocation()));
5096 }
5097 PArgs.clear();
5098
5099 // C++1z [temp.arg.template]p3:
5100 // If the rewrite produces an invalid type, then P is not at least as
5101 // specialized as A.
5102 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5103 Trap.hasErrorOccurred())
5104 return false;
5105 }
5106
5107 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5108 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5109
Richard Smith26b86ea2016-12-31 21:41:23 +00005110 // ... the function template corresponding to P is at least as specialized
5111 // as the function template corresponding to A according to the partial
5112 // ordering rules for function templates.
5113 TemplateDeductionInfo Info(Loc, A->getDepth());
5114 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5115}
5116
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005117/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005118/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005119static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005120MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005121 const Expr *E,
5122 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005123 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005124 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005125 // We can deduce from a pack expansion.
5126 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5127 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128
Richard Smith34349002012-07-09 03:07:20 +00005129 // Skip through any implicit casts we added while type-checking, and any
5130 // substitutions performed by template alias expansion.
5131 while (1) {
5132 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5133 E = ICE->getSubExpr();
5134 else if (const SubstNonTypeTemplateParmExpr *Subst =
5135 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5136 E = Subst->getReplacement();
5137 else
5138 break;
5139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005140
5141 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005142 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005143 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005144 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005145 return;
5146
Mike Stump11289f42009-09-09 15:08:12 +00005147 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005148 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5149 if (!NTTP)
5150 return;
5151
Douglas Gregor21610382009-10-29 00:04:11 +00005152 if (NTTP->getDepth() == Depth)
5153 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005154
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005155 // In C++17 mode, additional arguments may be deduced from the type of a
Richard Smith5f274382016-09-28 23:55:27 +00005156 // non-type argument.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005157 if (Ctx.getLangOpts().CPlusPlus17)
Richard Smith5f274382016-09-28 23:55:27 +00005158 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005159}
5160
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005161/// \brief Mark the template parameters that are used by the given
5162/// nested name specifier.
5163static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005164MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005165 NestedNameSpecifier *NNS,
5166 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005167 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005168 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005169 if (!NNS)
5170 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005172 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005173 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005174 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005175 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005176}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005178/// \brief Mark the template parameters that are used by the given
5179/// template name.
5180static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005181MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005182 TemplateName Name,
5183 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005184 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005185 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005186 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5187 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005188 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5189 if (TTP->getDepth() == Depth)
5190 Used[TTP->getIndex()] = true;
5191 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005192 return;
5193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005195 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005196 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005197 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005198 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005199 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005200 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005201}
5202
5203/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005204/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005205static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005206MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005207 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005208 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005209 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005210 if (T.isNull())
5211 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Douglas Gregor91772d12009-06-13 00:26:55 +00005213 // Non-dependent types have nothing deducible
5214 if (!T->isDependentType())
5215 return;
5216
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005217 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005218 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005219 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005220 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005221 cast<PointerType>(T)->getPointeeType(),
5222 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005223 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005224 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005225 break;
5226
5227 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005228 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005229 cast<BlockPointerType>(T)->getPointeeType(),
5230 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005231 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005232 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005233 break;
5234
5235 case Type::LValueReference:
5236 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005237 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005238 cast<ReferenceType>(T)->getPointeeType(),
5239 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005240 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005241 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005242 break;
5243
5244 case Type::MemberPointer: {
5245 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005246 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005247 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005248 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005249 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005250 break;
5251 }
5252
5253 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005254 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005255 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005256 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005257 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005258 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005259
5260 case Type::ConstantArray:
5261 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005262 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005263 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005264 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005265 break;
5266
5267 case Type::Vector:
5268 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005269 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005270 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005271 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005272 break;
5273
Douglas Gregor758a8692009-06-17 21:51:59 +00005274 case Type::DependentSizedExtVector: {
5275 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005276 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005277 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005278 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005279 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005280 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005281 break;
5282 }
5283
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005284 case Type::DependentAddressSpace: {
5285 const DependentAddressSpaceType *DependentASType =
5286 cast<DependentAddressSpaceType>(T);
5287 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5288 OnlyDeduced, Depth, Used);
5289 MarkUsedTemplateParameters(Ctx,
5290 DependentASType->getAddrSpaceExpr(),
5291 OnlyDeduced, Depth, Used);
5292 break;
5293 }
5294
Douglas Gregor91772d12009-06-13 00:26:55 +00005295 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005296 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005297 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5298 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005299 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5300 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005301 Depth, Used);
Richard Smithcd198152017-06-07 21:46:22 +00005302 if (auto *E = Proto->getNoexceptExpr())
5303 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005304 break;
5305 }
5306
Douglas Gregor21610382009-10-29 00:04:11 +00005307 case Type::TemplateTypeParm: {
5308 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5309 if (TTP->getDepth() == Depth)
5310 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005311 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005312 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005313
Douglas Gregorfb322d82011-01-14 05:11:40 +00005314 case Type::SubstTemplateTypeParmPack: {
5315 const SubstTemplateTypeParmPackType *Subst
5316 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005317 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005318 QualType(Subst->getReplacedParameter(), 0),
5319 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005320 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005321 OnlyDeduced, Depth, Used);
5322 break;
5323 }
5324
John McCall2408e322010-04-27 00:57:59 +00005325 case Type::InjectedClassName:
5326 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005327 LLVM_FALLTHROUGH;
John McCall2408e322010-04-27 00:57:59 +00005328
Douglas Gregor91772d12009-06-13 00:26:55 +00005329 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005330 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005331 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005332 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005333 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
Douglas Gregord0ad2942010-12-23 01:24:45 +00005335 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005336 // If the template argument list of P contains a pack expansion that is
5337 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005338 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005340 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005341 break;
5342
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005343 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005344 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005345 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005346 break;
5347 }
5348
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005349 case Type::Complex:
5350 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005351 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005352 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005353 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005354 break;
5355
Eli Friedman0dfb8892011-10-06 23:00:33 +00005356 case Type::Atomic:
5357 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005358 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005359 cast<AtomicType>(T)->getValueType(),
5360 OnlyDeduced, Depth, Used);
5361 break;
5362
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005363 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005364 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005365 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005366 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005367 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005368 break;
5369
John McCallc392f372010-06-11 00:33:02 +00005370 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005371 // C++14 [temp.deduct.type]p5:
5372 // The non-deduced contexts are:
5373 // -- The nested-name-specifier of a type that was specified using a
5374 // qualified-id
5375 //
5376 // C++14 [temp.deduct.type]p6:
5377 // When a type name is specified in a way that includes a non-deduced
5378 // context, all of the types that comprise that type name are also
5379 // non-deduced.
5380 if (OnlyDeduced)
5381 break;
5382
John McCallc392f372010-06-11 00:33:02 +00005383 const DependentTemplateSpecializationType *Spec
5384 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Richard Smith50d5b972015-12-30 20:56:05 +00005386 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5387 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005388
John McCallc392f372010-06-11 00:33:02 +00005389 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005390 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005391 Used);
5392 break;
5393 }
5394
John McCallbd8d9bd2010-03-01 23:49:17 +00005395 case Type::TypeOf:
5396 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005397 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005398 cast<TypeOfType>(T)->getUnderlyingType(),
5399 OnlyDeduced, Depth, Used);
5400 break;
5401
5402 case Type::TypeOfExpr:
5403 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005404 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005405 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5406 OnlyDeduced, Depth, Used);
5407 break;
5408
5409 case Type::Decltype:
5410 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005411 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005412 cast<DecltypeType>(T)->getUnderlyingExpr(),
5413 OnlyDeduced, Depth, Used);
5414 break;
5415
Alexis Hunte852b102011-05-24 22:41:36 +00005416 case Type::UnaryTransform:
5417 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005418 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005419 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005420 OnlyDeduced, Depth, Used);
5421 break;
5422
Douglas Gregord2fa7662010-12-20 02:24:11 +00005423 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005424 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005425 cast<PackExpansionType>(T)->getPattern(),
5426 OnlyDeduced, Depth, Used);
5427 break;
5428
Richard Smith30482bc2011-02-20 03:19:35 +00005429 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005430 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005431 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005432 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005433 OnlyDeduced, Depth, Used);
5434
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005435 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005436 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005437 case Type::VariableArray:
5438 case Type::FunctionNoProto:
5439 case Type::Record:
5440 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005441 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005442 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005443 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005444 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005445 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005446#define TYPE(Class, Base)
5447#define ABSTRACT_TYPE(Class, Base)
5448#define DEPENDENT_TYPE(Class, Base)
5449#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5450#include "clang/AST/TypeNodes.def"
5451 break;
5452 }
5453}
5454
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005455/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005456/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005457static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005458MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005459 const TemplateArgument &TemplateArg,
5460 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005461 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005462 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005463 switch (TemplateArg.getKind()) {
5464 case TemplateArgument::Null:
5465 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005466 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005467 break;
Mike Stump11289f42009-09-09 15:08:12 +00005468
Eli Friedmanb826a002012-09-26 02:36:12 +00005469 case TemplateArgument::NullPtr:
5470 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5471 Depth, Used);
5472 break;
5473
Douglas Gregor91772d12009-06-13 00:26:55 +00005474 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005475 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005476 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005477 break;
5478
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005479 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005480 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005481 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005482 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005483 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005484 break;
5485
5486 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005487 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005488 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005489 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490
Anders Carlssonbc343912009-06-15 17:04:53 +00005491 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005492 for (const auto &P : TemplateArg.pack_elements())
5493 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005494 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005495 }
5496}
5497
James Dennett41725122012-06-22 10:16:05 +00005498/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005499/// template argument list.
5500///
5501/// \param TemplateArgs the template argument list from which template
5502/// parameters will be deduced.
5503///
James Dennett41725122012-06-22 10:16:05 +00005504/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005505/// to indicate when the corresponding template parameter will be
5506/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005507void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005508Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005509 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005510 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005511 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005512 // If the template argument list of P contains a pack expansion that is not
5513 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005514 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005516 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005517 return;
5518
Douglas Gregor91772d12009-06-13 00:26:55 +00005519 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005520 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005521 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005522}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005523
5524/// \brief Marks all of the template parameters that will be deduced by a
5525/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005526void Sema::MarkDeducedTemplateParameters(
5527 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5528 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005530 = FunctionTemplate->getTemplateParameters();
5531 Deduced.clear();
5532 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Douglas Gregorce23bae2009-09-18 23:21:38 +00005534 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5535 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005536 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005537 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005538}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005539
Richard Smithf0393bf2017-02-16 04:22:56 +00005540bool hasDeducibleTemplateParameters(Sema &S,
5541 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005542 QualType T) {
5543 if (!T->isDependentType())
5544 return false;
5545
Richard Smithf0393bf2017-02-16 04:22:56 +00005546 TemplateParameterList *TemplateParams
5547 = FunctionTemplate->getTemplateParameters();
5548 llvm::SmallBitVector Deduced(TemplateParams->size());
5549 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5550 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005551
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005552 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005553}