blob: 0dcf52aec5958ad67d92b482dee16fce17feb7dc [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;
Richard Smithd92eddf2016-12-27 06:14:37 +0000347 if (!S.getLangOpts().CPlusPlus1z)
348 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
357 // Get the type of the parameter for deduction.
358 QualType ParamType = NTTP->getType();
359 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
360 ParamType = Expansion->getPattern();
361
Richard Smithd92eddf2016-12-27 06:14:37 +0000362 // FIXME: It's not clear how deduction of a parameter of reference
363 // type from an argument (of non-reference type) should be performed.
364 // For now, we just remove reference types from both sides and let
365 // the final check for matching types sort out the mess.
366 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000367 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000368 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
369 /*PartialOrdering=*/false,
370 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000371}
372
Mike Stump11289f42009-09-09 15:08:12 +0000373/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000374/// from the given integral constant.
375static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
376 Sema &S, TemplateParameterList *TemplateParams,
377 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
378 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
379 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
380 return DeduceNonTypeTemplateArgument(
381 S, TemplateParams, NTTP,
382 DeducedTemplateArgument(S.Context, Value, ValueType,
383 DeducedFromArrayBound),
384 ValueType, Info, Deduced);
385}
386
387/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000388/// from the given null pointer template argument type.
389static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000390 Sema &S, TemplateParameterList *TemplateParams,
391 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000392 TemplateDeductionInfo &Info,
393 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
394 Expr *Value =
395 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
396 S.Context.NullPtrTy, NTTP->getLocation()),
397 NullPtrType, CK_NullToPointer)
398 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000399 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
400 DeducedTemplateArgument(Value),
401 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000402}
403
404/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000405/// from the given type- or value-dependent expression.
406///
407/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000408static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
409 Sema &S, TemplateParameterList *TemplateParams,
410 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
411 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000412 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
413 DeducedTemplateArgument(Value),
414 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000415}
416
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000417/// \brief Deduce the value of the given non-type template parameter
418/// from the given declaration.
419///
420/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000421static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
422 Sema &S, TemplateParameterList *TemplateParams,
423 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
424 TemplateDeductionInfo &Info,
425 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000426 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000427 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000428 return DeduceNonTypeTemplateArgument(
429 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000430}
431
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000432static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000433DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000434 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000435 TemplateName Param,
436 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000437 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000438 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000439 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000440 if (!ParamDecl) {
441 // The parameter type is dependent and is not a template template parameter,
442 // so there is nothing that we can deduce.
443 return Sema::TDK_Success;
444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregoradee3e32009-11-11 23:06:43 +0000446 if (TemplateTemplateParmDecl *TempParam
447 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000448 // If we're not deducing at this depth, there's nothing to deduce.
449 if (TempParam->getDepth() != Info.getDeducedDepth())
450 return Sema::TDK_Success;
451
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000452 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000454 Deduced[TempParam->getIndex()],
455 NewDeduced);
456 if (Result.isNull()) {
457 Info.Param = TempParam;
458 Info.FirstArg = Deduced[TempParam->getIndex()];
459 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000463 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466
Douglas Gregoradee3e32009-11-11 23:06:43 +0000467 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000468 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000469 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregoradee3e32009-11-11 23:06:43 +0000471 // Mismatch of non-dependent template parameter to argument.
472 Info.FirstArg = TemplateArgument(Param);
473 Info.SecondArg = TemplateArgument(Arg);
474 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000475}
476
Mike Stump11289f42009-09-09 15:08:12 +0000477/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000478/// type (which is a template-id) with the template argument type.
479///
Chandler Carruthc1263112010-02-07 21:33:28 +0000480/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000481///
482/// \param TemplateParams the template parameters that we are deducing
483///
484/// \param Param the parameter type
485///
486/// \param Arg the argument type
487///
488/// \param Info information about the template argument deduction itself
489///
490/// \param Deduced the deduced template arguments
491///
492/// \returns the result of template argument deduction so far. Note that a
493/// "success" result means that template argument deduction has not yet failed,
494/// but it may still fail, later, for other reasons.
495static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000496DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000497 TemplateParameterList *TemplateParams,
498 const TemplateSpecializationType *Param,
499 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000500 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000501 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000502 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000503
Douglas Gregore81f3e72009-07-07 23:09:34 +0000504 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000505 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 = dyn_cast<TemplateSpecializationType>(Arg)) {
507 // Perform template argument deduction for the template name.
508 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000509 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 Param->getTemplateName(),
511 SpecArg->getTemplateName(),
512 Info, Deduced))
513 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Mike Stump11289f42009-09-09 15:08:12 +0000515
Douglas Gregore81f3e72009-07-07 23:09:34 +0000516 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000517 // argument. Ignore any missing/extra arguments, since they could be
518 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000519 return DeduceTemplateArguments(S, TemplateParams,
520 Param->template_arguments(),
521 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000522 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
Douglas Gregore81f3e72009-07-07 23:09:34 +0000525 // If the argument type is a class template specialization, we
526 // perform template argument deduction using its template
527 // arguments.
528 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 if (!RecordArg) {
530 Info.FirstArg = TemplateArgument(QualType(Param, 0));
531 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000532 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
535 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000536 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 if (!SpecArg) {
538 Info.FirstArg = TemplateArgument(QualType(Param, 0));
539 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000540 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Douglas Gregore81f3e72009-07-07 23:09:34 +0000543 // Perform template argument deduction for the template name.
544 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000545 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000546 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000547 Param->getTemplateName(),
548 TemplateName(SpecArg->getSpecializedTemplate()),
549 Info, Deduced))
550 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000551
Douglas Gregor7baabef2010-12-22 18:17:10 +0000552 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000553 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
554 SpecArg->getTemplateArgs().asArray(), Info,
555 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000556}
557
John McCall08569062010-08-28 22:14:41 +0000558/// \brief Determines whether the given type is an opaque type that
559/// might be more qualified when instantiated.
560static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
561 switch (T->getTypeClass()) {
562 case Type::TypeOfExpr:
563 case Type::TypeOf:
564 case Type::DependentName:
565 case Type::Decltype:
566 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000567 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000568 return true;
569
570 case Type::ConstantArray:
571 case Type::IncompleteArray:
572 case Type::VariableArray:
573 case Type::DependentSizedArray:
574 return IsPossiblyOpaquelyQualifiedType(
575 cast<ArrayType>(T)->getElementType());
576
577 default:
578 return false;
579 }
580}
581
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000582/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000584getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000585 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
586 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor5499af42011-01-05 23:12:31 +0000588 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
589 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor5499af42011-01-05 23:12:31 +0000591 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
592 return std::make_pair(TTP->getDepth(), TTP->getIndex());
593}
594
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000595/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000597getDepthAndIndex(UnexpandedParameterPack UPP) {
598 if (const TemplateTypeParmType *TTP
599 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
600 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000602 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
603}
604
Douglas Gregor5499af42011-01-05 23:12:31 +0000605/// \brief Helper function to build a TemplateParameter when we don't
606/// know its type statically.
607static TemplateParameter makeTemplateParameter(Decl *D) {
608 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
609 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000610 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000611 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregor5499af42011-01-05 23:12:31 +0000613 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
614}
615
Richard Smith0a80d572014-05-29 01:12:14 +0000616/// A pack that we're currently deducing.
617struct clang::DeducedPack {
618 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000619
Richard Smith0a80d572014-05-29 01:12:14 +0000620 // The index of the pack.
621 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Richard Smith0a80d572014-05-29 01:12:14 +0000623 // The old value of the pack before we started deducing it.
624 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000625
Richard Smith0a80d572014-05-29 01:12:14 +0000626 // A deferred value of this pack from an inner deduction, that couldn't be
627 // deduced because this deduction hadn't happened yet.
628 DeducedTemplateArgument DeferredDeduction;
629
630 // The new value of the pack.
631 SmallVector<DeducedTemplateArgument, 4> New;
632
633 // The outer deduction for this pack, if any.
634 DeducedPack *Outer;
635};
636
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000637namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000638/// A scope in which we're performing pack deduction.
639class PackDeductionScope {
640public:
641 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
642 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
643 TemplateDeductionInfo &Info, TemplateArgument Pattern)
644 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith130cc442017-02-21 23:49:18 +0000645 // Dig out the partially-substituted pack, if there is one.
646 const TemplateArgument *PartialPackArgs = nullptr;
647 unsigned NumPartialPackArgs = 0;
648 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
649 if (auto *Scope = S.CurrentInstantiationScope)
650 if (auto *Partial = Scope->getPartiallySubstitutedPack(
651 &PartialPackArgs, &NumPartialPackArgs))
652 PartialPackDepthIndex = getDepthAndIndex(Partial);
653
Richard Smith0a80d572014-05-29 01:12:14 +0000654 // Compute the set of template parameter indices that correspond to
655 // parameter packs expanded by the pack expansion.
656 {
657 llvm::SmallBitVector SawIndices(TemplateParams->size());
Richard Smith130cc442017-02-21 23:49:18 +0000658
659 auto AddPack = [&](unsigned Index) {
660 if (SawIndices[Index])
661 return;
662 SawIndices[Index] = true;
663
664 // Save the deduced template argument for the parameter pack expanded
665 // by this pack expansion, then clear out the deduction.
666 DeducedPack Pack(Index);
667 Pack.Saved = Deduced[Index];
668 Deduced[Index] = TemplateArgument();
669
670 Packs.push_back(Pack);
671 };
672
673 // First look for unexpanded packs in the pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000674 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
675 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
676 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
677 unsigned Depth, Index;
678 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith130cc442017-02-21 23:49:18 +0000679 if (Depth == Info.getDeducedDepth())
680 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000681 }
Richard Smith130cc442017-02-21 23:49:18 +0000682 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
683
684 // This pack expansion will have been partially expanded iff the only
685 // unexpanded parameter pack within it is the partially-substituted pack.
686 IsPartiallyExpanded =
687 Packs.size() == 1 &&
688 PartialPackDepthIndex ==
689 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
690
691 // Skip over the pack elements that were expanded into separate arguments.
692 if (IsPartiallyExpanded)
693 PackElements += NumPartialPackArgs;
694
695 // We can also have deduced template parameters that do not actually
696 // appear in the pattern, but can be deduced by it (the type of a non-type
697 // template parameter pack, in particular). These won't have prevented us
698 // from partially expanding the pack.
699 llvm::SmallBitVector Used(TemplateParams->size());
700 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
701 Info.getDeducedDepth(), Used);
702 for (int Index = Used.find_first(); Index != -1;
703 Index = Used.find_next(Index))
704 if (TemplateParams->getParam(Index)->isParameterPack())
705 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000706 }
Richard Smith0a80d572014-05-29 01:12:14 +0000707
708 for (auto &Pack : Packs) {
709 if (Info.PendingDeducedPacks.size() > Pack.Index)
710 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
711 else
712 Info.PendingDeducedPacks.resize(Pack.Index + 1);
713 Info.PendingDeducedPacks[Pack.Index] = &Pack;
714
Richard Smith130cc442017-02-21 23:49:18 +0000715 if (PartialPackDepthIndex ==
716 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
717 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
718 // We pre-populate the deduced value of the partially-substituted
719 // pack with the specified value. This is not entirely correct: the
720 // value is supposed to have been substituted, not deduced, but the
721 // cases where this is observable require an exact type match anyway.
722 //
723 // FIXME: If we could represent a "depth i, index j, pack elem k"
724 // parameter, we could substitute the partially-substituted pack
725 // everywhere and avoid this.
726 if (Pack.New.size() > PackElements)
727 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000728 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000729 }
730 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000731
Richard Smith0a80d572014-05-29 01:12:14 +0000732 ~PackDeductionScope() {
733 for (auto &Pack : Packs)
734 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
Richard Smithde0d34a2017-01-09 07:14:40 +0000737 /// Determine whether this pack has already been partially expanded into a
738 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000739 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000740
Richard Smith0a80d572014-05-29 01:12:14 +0000741 /// Move to deducing the next element in each pack that is being deduced.
742 void nextPackElement() {
743 // Capture the deduced template arguments for each parameter pack expanded
744 // by this pack expansion, add them to the list of arguments we've deduced
745 // for that pack, then clear out the deduced argument.
746 for (auto &Pack : Packs) {
747 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000748 if (!Pack.New.empty() || !DeducedArg.isNull()) {
749 while (Pack.New.size() < PackElements)
750 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000751 if (Pack.New.size() == PackElements)
752 Pack.New.push_back(DeducedArg);
753 else
754 Pack.New[PackElements] = DeducedArg;
755 DeducedArg = Pack.New.size() > PackElements + 1
756 ? Pack.New[PackElements + 1]
757 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000758 }
759 }
Richard Smith539e8e32017-01-04 01:48:55 +0000760 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000761 }
762
763 /// \brief Finish template argument deduction for a set of argument packs,
764 /// producing the argument packs and checking for consistency with prior
765 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000766 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000767 // Build argument packs for each of the parameter packs expanded by this
768 // pack expansion.
769 for (auto &Pack : Packs) {
770 // Put back the old value for this pack.
771 Deduced[Pack.Index] = Pack.Saved;
772
773 // Build or find a new value for this pack.
774 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000775 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000776 if (Pack.DeferredDeduction.isNull()) {
777 // We were not able to deduce anything for this parameter pack
778 // (because it only appeared in non-deduced contexts), so just
779 // restore the saved argument pack.
780 continue;
781 }
782
783 NewPack = Pack.DeferredDeduction;
784 Pack.DeferredDeduction = TemplateArgument();
785 } else if (Pack.New.empty()) {
786 // If we deduced an empty argument pack, create it now.
787 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
788 } else {
789 TemplateArgument *ArgumentPack =
790 new (S.Context) TemplateArgument[Pack.New.size()];
791 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
792 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000793 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000794 // FIXME: This is wrong, it's possible that some pack elements are
795 // deduced from an array bound and others are not:
796 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
797 // g({1, 2, 3}, {{}, {}});
798 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000799 Pack.New[0].wasDeducedFromArrayBound());
800 }
801
802 // Pick where we're going to put the merged pack.
803 DeducedTemplateArgument *Loc;
804 if (Pack.Outer) {
805 if (Pack.Outer->DeferredDeduction.isNull()) {
806 // Defer checking this pack until we have a complete pack to compare
807 // it against.
808 Pack.Outer->DeferredDeduction = NewPack;
809 continue;
810 }
811 Loc = &Pack.Outer->DeferredDeduction;
812 } else {
813 Loc = &Deduced[Pack.Index];
814 }
815
816 // Check the new pack matches any previous value.
817 DeducedTemplateArgument OldPack = *Loc;
818 DeducedTemplateArgument Result =
819 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
820
821 // If we deferred a deduction of this pack, check that one now too.
822 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
823 OldPack = Result;
824 NewPack = Pack.DeferredDeduction;
825 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
826 }
827
828 if (Result.isNull()) {
829 Info.Param =
830 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
831 Info.FirstArg = OldPack;
832 Info.SecondArg = NewPack;
833 return Sema::TDK_Inconsistent;
834 }
835
836 *Loc = Result;
837 }
838
839 return Sema::TDK_Success;
840 }
841
842private:
843 Sema &S;
844 TemplateParameterList *TemplateParams;
845 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
846 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000847 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000848 bool IsPartiallyExpanded = false;
Richard Smith0a80d572014-05-29 01:12:14 +0000849
850 SmallVector<DeducedPack, 2> Packs;
851};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000852} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855/// types to the list of argument types, as in the parameter-type-lists of
856/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000857///
858/// \param S The semantic analysis object within which we are deducing
859///
860/// \param TemplateParams The template parameters that we are deducing
861///
862/// \param Params The list of parameter types
863///
864/// \param NumParams The number of types in \c Params
865///
866/// \param Args The list of argument types
867///
868/// \param NumArgs The number of types in \c Args
869///
870/// \param Info information about the template argument deduction itself
871///
872/// \param Deduced the deduced template arguments
873///
874/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
875/// how template argument deduction is performed.
876///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000877/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000879/// (C++0x [temp.deduct.partial]).
880///
Douglas Gregor5499af42011-01-05 23:12:31 +0000881/// \returns the result of template argument deduction so far. Note that a
882/// "success" result means that template argument deduction has not yet failed,
883/// but it may still fail, later, for other reasons.
884static Sema::TemplateDeductionResult
885DeduceTemplateArguments(Sema &S,
886 TemplateParameterList *TemplateParams,
887 const QualType *Params, unsigned NumParams,
888 const QualType *Args, unsigned NumArgs,
889 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000890 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000891 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000892 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000893 // Fast-path check to see if we have too many/too few arguments.
894 if (NumParams != NumArgs &&
895 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
896 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000897 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000898
Douglas Gregor5499af42011-01-05 23:12:31 +0000899 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900 // Similarly, if P has a form that contains (T), then each parameter type
901 // Pi of the respective parameter-type- list of P is compared with the
902 // corresponding parameter type Ai of the corresponding parameter-type-list
903 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000904 unsigned ArgIdx = 0, ParamIdx = 0;
905 for (; ParamIdx != NumParams; ++ParamIdx) {
906 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000908 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
909 if (!Expansion) {
910 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000911
Douglas Gregor5499af42011-01-05 23:12:31 +0000912 // Make sure we have an argument.
913 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000914 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000916 if (isa<PackExpansionType>(Args[ArgIdx])) {
917 // C++0x [temp.deduct.type]p22:
918 // If the original function parameter associated with A is a function
919 // parameter pack and the function parameter associated with P is not
920 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000921 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
Douglas Gregor5499af42011-01-05 23:12:31 +0000924 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000925 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
926 Params[ParamIdx], Args[ArgIdx],
927 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000928 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000929 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930
Douglas Gregor5499af42011-01-05 23:12:31 +0000931 ++ArgIdx;
932 continue;
933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000934
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000935 // C++0x [temp.deduct.type]p5:
936 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000938 // parameter-declaration-clause.
939 if (ParamIdx + 1 < NumParams)
940 return Sema::TDK_Success;
941
Douglas Gregor5499af42011-01-05 23:12:31 +0000942 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000943 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000944 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000946 // comparison deduces template arguments for subsequent positions in the
947 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000948
Douglas Gregor5499af42011-01-05 23:12:31 +0000949 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000950 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951
Douglas Gregor5499af42011-01-05 23:12:31 +0000952 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000953 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000955 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
956 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000957 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000958 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000959
Richard Smith0a80d572014-05-29 01:12:14 +0000960 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962
Douglas Gregor5499af42011-01-05 23:12:31 +0000963 // Build argument packs for each of the parameter packs expanded by this
964 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000965 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000968
Douglas Gregor5499af42011-01-05 23:12:31 +0000969 // Make sure we don't have any extra arguments.
970 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000971 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
Douglas Gregor5499af42011-01-05 23:12:31 +0000973 return Sema::TDK_Success;
974}
975
Douglas Gregor1d684c22011-04-28 00:56:09 +0000976/// \brief Determine whether the parameter has qualifiers that are either
977/// inconsistent with or a superset of the argument's qualifiers.
978static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
979 QualType ArgType) {
980 Qualifiers ParamQs = ParamType.getQualifiers();
981 Qualifiers ArgQs = ArgType.getQualifiers();
982
983 if (ParamQs == ArgQs)
984 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000985
Douglas Gregor1d684c22011-04-28 00:56:09 +0000986 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000987 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000988 ParamQs.hasObjCGCAttr())
989 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000990
Douglas Gregor1d684c22011-04-28 00:56:09 +0000991 // Mismatched (but not missing) address spaces.
992 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
993 ParamQs.hasAddressSpace())
994 return true;
995
John McCall31168b02011-06-15 23:02:42 +0000996 // Mismatched (but not missing) Objective-C lifetime qualifiers.
997 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
998 ParamQs.hasObjCLifetime())
999 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001000
Douglas Gregor1d684c22011-04-28 00:56:09 +00001001 // CVR qualifier superset.
1002 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
1003 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
1004 == ParamQs.getCVRQualifiers());
1005}
1006
Douglas Gregor19a41f12013-04-17 08:45:07 +00001007/// \brief Compare types for equality with respect to possibly compatible
1008/// function types (noreturn adjustment, implicit calling conventions). If any
1009/// of parameter and argument is not a function, just perform type comparison.
1010///
1011/// \param Param the template parameter type.
1012///
1013/// \param Arg the argument type.
1014bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1015 CanQualType Arg) {
1016 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1017 *ArgFunction = Arg->getAs<FunctionType>();
1018
1019 // Just compare if not functions.
1020 if (!ParamFunction || !ArgFunction)
1021 return Param == Arg;
1022
Richard Smith3c4f8d22016-10-16 17:54:23 +00001023 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001024 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001025 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001026 return Arg == Context.getCanonicalType(AdjustedParam);
1027
1028 // FIXME: Compatible calling conventions.
1029
1030 return Param == Arg;
1031}
1032
Richard Smith32918772017-02-14 00:25:28 +00001033/// Get the index of the first template parameter that was originally from the
1034/// innermost template-parameter-list. This is 0 except when we concatenate
1035/// the template parameter lists of a class template and a constructor template
1036/// when forming an implicit deduction guide.
1037static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001038 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1039 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001040 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001041 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001042}
1043
1044/// Determine whether a type denotes a forwarding reference.
1045static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1046 // C++1z [temp.deduct.call]p3:
1047 // A forwarding reference is an rvalue reference to a cv-unqualified
1048 // template parameter that does not represent a template parameter of a
1049 // class template.
1050 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1051 if (ParamRef->getPointeeType().getQualifiers())
1052 return false;
1053 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1054 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1055 }
1056 return false;
1057}
1058
Douglas Gregorcceb9752009-06-26 18:27:22 +00001059/// \brief Deduce the template arguments by comparing the parameter type and
1060/// the argument type (C++ [temp.deduct.type]).
1061///
Chandler Carruthc1263112010-02-07 21:33:28 +00001062/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001063///
1064/// \param TemplateParams the template parameters that we are deducing
1065///
1066/// \param ParamIn the parameter type
1067///
1068/// \param ArgIn the argument type
1069///
1070/// \param Info information about the template argument deduction itself
1071///
1072/// \param Deduced the deduced template arguments
1073///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001074/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001075/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001076///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001077/// \param PartialOrdering Whether we're performing template argument deduction
1078/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1079///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001080/// \returns the result of template argument deduction so far. Note that a
1081/// "success" result means that template argument deduction has not yet failed,
1082/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001083static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001084DeduceTemplateArgumentsByTypeMatch(Sema &S,
1085 TemplateParameterList *TemplateParams,
1086 QualType ParamIn, QualType ArgIn,
1087 TemplateDeductionInfo &Info,
1088 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1089 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001090 bool PartialOrdering,
1091 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001092 // We only want to look at the canonical types, since typedefs and
1093 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001094 QualType Param = S.Context.getCanonicalType(ParamIn);
1095 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001096
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001097 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001099 if (const PackExpansionType *ArgExpansion
1100 = dyn_cast<PackExpansionType>(Arg))
1101 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Douglas Gregorb837ea42011-01-11 17:34:58 +00001103 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001104 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105 // Before the partial ordering is done, certain transformations are
1106 // performed on the types used for partial ordering:
1107 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001108 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1109 if (ParamRef)
1110 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Douglas Gregorb837ea42011-01-11 17:34:58 +00001112 // - If A is a reference type, A is replaced by the type referred to.
1113 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1114 if (ArgRef)
1115 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
Richard Smithed563c22015-02-20 04:45:22 +00001117 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1118 // C++11 [temp.deduct.partial]p9:
1119 // If, for a given type, deduction succeeds in both directions (i.e.,
1120 // the types are identical after the transformations above) and both
1121 // P and A were reference types [...]:
1122 // - if [one type] was an lvalue reference and [the other type] was
1123 // not, [the other type] is not considered to be at least as
1124 // specialized as [the first type]
1125 // - if [one type] is more cv-qualified than [the other type],
1126 // [the other type] is not considered to be at least as specialized
1127 // as [the first type]
1128 // Objective-C ARC adds:
1129 // - [one type] has non-trivial lifetime, [the other type] has
1130 // __unsafe_unretained lifetime, and the types are otherwise
1131 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001132 //
Richard Smithed563c22015-02-20 04:45:22 +00001133 // A is "considered to be at least as specialized" as P iff deduction
1134 // succeeds, so we model this as a deduction failure. Note that
1135 // [the first type] is P and [the other type] is A here; the standard
1136 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001137 Qualifiers ParamQuals = Param.getQualifiers();
1138 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001139 if ((ParamRef->isLValueReferenceType() &&
1140 !ArgRef->isLValueReferenceType()) ||
1141 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1142 (ParamQuals.hasNonTrivialObjCLifetime() &&
1143 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1144 ParamQuals.withoutObjCLifetime() ==
1145 ArgQuals.withoutObjCLifetime())) {
1146 Info.FirstArg = TemplateArgument(ParamIn);
1147 Info.SecondArg = TemplateArgument(ArgIn);
1148 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001149 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151
Richard Smithed563c22015-02-20 04:45:22 +00001152 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001153 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001154 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001155 // version of P.
1156 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001158 // version of A.
1159 Arg = Arg.getUnqualifiedType();
1160 } else {
1161 // C++0x [temp.deduct.call]p4 bullet 1:
1162 // - If the original P is a reference type, the deduced A (i.e., the type
1163 // referred to by the reference) can be more cv-qualified than the
1164 // transformed A.
1165 if (TDF & TDF_ParamWithReferenceType) {
1166 Qualifiers Quals;
1167 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1168 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001169 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001170 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1171 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
Douglas Gregor85f240c2011-01-25 17:19:08 +00001173 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1174 // C++0x [temp.deduct.type]p10:
1175 // If P and A are function types that originated from deduction when
1176 // taking the address of a function template (14.8.2.2) or when deducing
1177 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001179 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1180 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001182 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1183 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001184 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001185 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001186 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1187 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001188 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001191 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001192 // A template type argument T, a template template argument TT or a
1193 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001194 // the following forms:
1195 //
1196 // T
1197 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001198 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001199 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001200 // Just skip any attempts to deduce from a placeholder type or a parameter
1201 // at a different depth.
1202 if (Arg->isPlaceholderType() ||
1203 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001204 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001205
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001206 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001207 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001208
Douglas Gregor60454822009-07-22 20:02:25 +00001209 // If the argument type is an array type, move the qualifiers up to the
1210 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001211 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001212 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001213 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001214 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001215 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001216 RecanonicalizeArg = true;
1217 }
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001220 // The argument type can not be less qualified than the parameter
1221 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001222 if (!(TDF & TDF_IgnoreQualifiers) &&
1223 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001224 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001225 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001226 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001227 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001228 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001229
Richard Smith87d263e2016-12-25 08:05:23 +00001230 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1231 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001232 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001233 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001234
Douglas Gregor1d684c22011-04-28 00:56:09 +00001235 // Remove any qualifiers on the parameter from the deduced type.
1236 // We checked the qualifiers for consistency above.
1237 Qualifiers DeducedQs = DeducedType.getQualifiers();
1238 Qualifiers ParamQs = Param.getQualifiers();
1239 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1240 if (ParamQs.hasObjCGCAttr())
1241 DeducedQs.removeObjCGCAttr();
1242 if (ParamQs.hasAddressSpace())
1243 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001244 if (ParamQs.hasObjCLifetime())
1245 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001246
Douglas Gregore46db902011-06-17 22:11:49 +00001247 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001248 // If template deduction would produce a lifetime qualifier on a type
1249 // that is not a lifetime type, template argument deduction fails.
1250 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1251 !DeducedType->isDependentType()) {
1252 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1253 Info.FirstArg = TemplateArgument(Param);
1254 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001255 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001256 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001257
Douglas Gregora4f2b432011-07-26 14:53:44 +00001258 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001259 // If template deduction would produce an argument type with lifetime type
1260 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001261 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001262 DeducedType->isObjCLifetimeType() &&
1263 !DeducedQs.hasObjCLifetime())
1264 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001265
Douglas Gregor1d684c22011-04-28 00:56:09 +00001266 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1267 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001268
Douglas Gregord6605db2009-07-22 21:30:48 +00001269 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001270 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Richard Smith5f274382016-09-28 23:55:27 +00001272 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001274 Deduced[Index],
1275 NewDeduced);
1276 if (Result.isNull()) {
1277 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1278 Info.FirstArg = Deduced[Index];
1279 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001282
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001283 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001285 }
1286
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001287 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001288 Info.FirstArg = TemplateArgument(ParamIn);
1289 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001290
Douglas Gregorfb322d82011-01-14 05:11:40 +00001291 // If the parameter is an already-substituted template parameter
1292 // pack, do nothing: we don't know which of its arguments to look
1293 // at, so we have to wait until all of the parameter packs in this
1294 // expansion have arguments.
1295 if (isa<SubstTemplateTypeParmPackType>(Param))
1296 return Sema::TDK_Success;
1297
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001298 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001299 CanQualType CanParam = S.Context.getCanonicalType(Param);
1300 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001301 if (!(TDF & TDF_IgnoreQualifiers)) {
1302 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001303 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001304 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001305 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001306 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001307 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001308 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001309
Douglas Gregor194ea692012-03-11 03:29:50 +00001310 // If the parameter type is not dependent, there is nothing to deduce.
1311 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001312 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001313 bool NonDeduced =
1314 (TDF & TDF_AllowCompatibleFunctionType)
1315 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1316 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001317 if (NonDeduced) {
1318 return Sema::TDK_NonDeducedMismatch;
1319 }
1320 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001321 return Sema::TDK_Success;
1322 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001323 } else if (!Param->isDependentType()) {
1324 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1325 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001326 bool Success =
1327 (TDF & TDF_AllowCompatibleFunctionType)
1328 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1329 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001330 if (Success)
1331 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001332 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001333
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001334 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001335 // Non-canonical types cannot appear here.
1336#define NON_CANONICAL_TYPE(Class, Base) \
1337 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1338#define TYPE(Class, Base)
1339#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001340
Douglas Gregor39c02722011-06-15 16:02:29 +00001341 case Type::TemplateTypeParm:
1342 case Type::SubstTemplateTypeParmPack:
1343 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001344
1345 // These types cannot be dependent, so simply check whether the types are
1346 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001347 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001348 case Type::VariableArray:
1349 case Type::Vector:
1350 case Type::FunctionNoProto:
1351 case Type::Record:
1352 case Type::Enum:
1353 case Type::ObjCObject:
1354 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001355 case Type::ObjCObjectPointer: {
1356 if (TDF & TDF_SkipNonDependent)
1357 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001358
Douglas Gregor194ea692012-03-11 03:29:50 +00001359 if (TDF & TDF_IgnoreQualifiers) {
1360 Param = Param.getUnqualifiedType();
1361 Arg = Arg.getUnqualifiedType();
1362 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001363
Douglas Gregor194ea692012-03-11 03:29:50 +00001364 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1365 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001366
1367 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001368 case Type::Complex:
1369 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001370 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1371 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001372 ComplexArg->getElementType(),
1373 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001374
1375 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001376
1377 // _Atomic T [extension]
1378 case Type::Atomic:
1379 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001380 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001381 cast<AtomicType>(Param)->getValueType(),
1382 AtomicArg->getValueType(),
1383 Info, Deduced, TDF);
1384
1385 return Sema::TDK_NonDeducedMismatch;
1386
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001388 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001389 QualType PointeeType;
1390 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1391 PointeeType = PointerArg->getPointeeType();
1392 } else if (const ObjCObjectPointerType *PointerArg
1393 = Arg->getAs<ObjCObjectPointerType>()) {
1394 PointeeType = PointerArg->getPointeeType();
1395 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001397 }
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregorfc516c92009-06-26 23:27:24 +00001399 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001400 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1401 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001402 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001403 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001406 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001407 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001408 const LValueReferenceType *ReferenceArg =
1409 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001410 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001411 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001413 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001414 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001415 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001416 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001417
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001418 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001419 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001420 const RValueReferenceType *ReferenceArg =
1421 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001422 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001423 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001424
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001425 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1426 cast<RValueReferenceType>(Param)->getPointeeType(),
1427 ReferenceArg->getPointeeType(),
1428 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001429 }
Mike Stump11289f42009-09-09 15:08:12 +00001430
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001431 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001432 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001433 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001434 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001435 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001436 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001437
John McCallf7332682010-08-19 00:20:19 +00001438 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001439 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1440 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1441 IncompleteArrayArg->getElementType(),
1442 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001443 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001444
1445 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001446 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001447 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001448 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001449 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001450 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001451
1452 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001453 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001454 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001455 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCallf7332682010-08-19 00:20:19 +00001457 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001458 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1459 ConstantArrayParm->getElementType(),
1460 ConstantArrayArg->getElementType(),
1461 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001462 }
1463
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001464 // type [i]
1465 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001466 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001467 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001468 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001469
John McCallf7332682010-08-19 00:20:19 +00001470 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1471
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001472 // Check the element type of the arrays
1473 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001474 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001475 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001476 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1477 DependentArrayParm->getElementType(),
1478 ArrayArg->getElementType(),
1479 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001480 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001481
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001482 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001483 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001484 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001485 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001486 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001487
1488 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001489 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001490 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1491 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001492 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001493 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1494 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001495 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001496 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001497 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001498 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001499 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001500 if (const DependentSizedArrayType *DependentArrayArg
1501 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001502 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001503 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001504 DependentArrayArg->getSizeExpr(),
1505 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001507 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001508 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
1511 // type(*)(T)
1512 // T(*)()
1513 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001514 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001515 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001516 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001517 dyn_cast<FunctionProtoType>(Arg);
1518 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001519 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001520
1521 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001522 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001523
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001525 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001526 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001527 != FunctionProtoArg->getRefQualifier() ||
1528 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001529 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001530
Anders Carlsson2128ec72009-06-08 15:19:08 +00001531 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001532 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1533 S, TemplateParams, FunctionProtoParam->getReturnType(),
1534 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001535 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Richard Smithcd198152017-06-07 21:46:22 +00001537 // Check parameter types.
1538 if (auto Result = DeduceTemplateArguments(
1539 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1540 FunctionProtoParam->getNumParams(),
1541 FunctionProtoArg->param_type_begin(),
1542 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1543 return Result;
1544
1545 if (TDF & TDF_AllowCompatibleFunctionType)
1546 return Sema::TDK_Success;
1547
1548 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1549 // deducing through the noexcept-specifier if it's part of the canonical
1550 // type. libstdc++ relies on this.
1551 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1552 if (NonTypeTemplateParmDecl *NTTP =
1553 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1554 : nullptr) {
1555 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1556 "saw non-type template parameter with wrong depth");
1557
1558 llvm::APSInt Noexcept(1);
1559 switch (FunctionProtoArg->canThrow(S.Context)) {
1560 case CT_Cannot:
1561 Noexcept = 1;
1562 LLVM_FALLTHROUGH;
1563
1564 case CT_Can:
1565 // We give E in noexcept(E) the "deduced from array bound" treatment.
1566 // FIXME: Should we?
1567 return DeduceNonTypeTemplateArgument(
1568 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1569 /*ArrayBound*/true, Info, Deduced);
1570
1571 case CT_Dependent:
1572 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1573 return DeduceNonTypeTemplateArgument(
1574 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1575 // Can't deduce anything from throw(T...).
1576 break;
1577 }
1578 }
1579 // FIXME: Detect non-deduced exception specification mismatches?
1580
1581 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
John McCalle78aac42010-03-10 03:28:59 +00001584 case Type::InjectedClassName: {
1585 // Treat a template's injected-class-name as if the template
1586 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001587 Param = cast<InjectedClassNameType>(Param)
1588 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001589 assert(isa<TemplateSpecializationType>(Param) &&
1590 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001591 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001592 }
1593
Douglas Gregor705c9002009-06-26 20:57:09 +00001594 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001595 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001596 // TT<T>
1597 // TT<i>
1598 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001599 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001600 const TemplateSpecializationType *SpecParam =
1601 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001602
Richard Smith9b296e32016-04-25 19:09:05 +00001603 // When Arg cannot be a derived class, we can just try to deduce template
1604 // arguments from the template-id.
1605 const RecordType *RecordT = Arg->getAs<RecordType>();
1606 if (!(TDF & TDF_DerivedClass) || !RecordT)
1607 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1608 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Richard Smith9b296e32016-04-25 19:09:05 +00001610 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1611 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001612
Richard Smith9b296e32016-04-25 19:09:05 +00001613 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1614 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Richard Smith9b296e32016-04-25 19:09:05 +00001616 if (Result == Sema::TDK_Success)
1617 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Richard Smith9b296e32016-04-25 19:09:05 +00001619 // We cannot inspect base classes as part of deduction when the type
1620 // is incomplete, so either instantiate any templates necessary to
1621 // complete the type, or skip over it if it cannot be completed.
1622 if (!S.isCompleteType(Info.getLocation(), Arg))
1623 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001624
Richard Smith9b296e32016-04-25 19:09:05 +00001625 // C++14 [temp.deduct.call] p4b3:
1626 // If P is a class and P has the form simple-template-id, then the
1627 // transformed A can be a derived class of the deduced A. Likewise if
1628 // P is a pointer to a class of the form simple-template-id, the
1629 // transformed A can be a pointer to a derived class pointed to by the
1630 // deduced A.
1631 //
1632 // These alternatives are considered only if type deduction would
1633 // otherwise fail. If they yield more than one possible deduced A, the
1634 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001635
Faisal Vali683b0742016-05-19 02:28:21 +00001636 // Reset the incorrectly deduced argument from above.
1637 Deduced = DeducedOrig;
1638
1639 // Use data recursion to crawl through the list of base classes.
1640 // Visited contains the set of nodes we have already visited, while
1641 // ToVisit is our stack of records that we still need to visit.
1642 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1643 SmallVector<const RecordType *, 8> ToVisit;
1644 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001645 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001646 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001647 while (!ToVisit.empty()) {
1648 // Retrieve the next class in the inheritance hierarchy.
1649 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001650
Faisal Vali683b0742016-05-19 02:28:21 +00001651 // If we have already seen this type, skip it.
1652 if (!Visited.insert(NextT).second)
1653 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001654
Faisal Vali683b0742016-05-19 02:28:21 +00001655 // If this is a base class, try to perform template argument
1656 // deduction from it.
1657 if (NextT != RecordT) {
1658 TemplateDeductionInfo BaseInfo(Info.getLocation());
1659 Sema::TemplateDeductionResult BaseResult =
1660 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1661 QualType(NextT, 0), BaseInfo, Deduced);
1662
1663 // If template argument deduction for this base was successful,
1664 // note that we had some success. Otherwise, ignore any deductions
1665 // from this base class.
1666 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001667 // If we've already seen some success, then deduction fails due to
1668 // an ambiguity (temp.deduct.call p5).
1669 if (Successful)
1670 return Sema::TDK_MiscellaneousDeductionFailure;
1671
Faisal Vali683b0742016-05-19 02:28:21 +00001672 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001673 std::swap(SuccessfulDeduced, Deduced);
1674
Faisal Vali683b0742016-05-19 02:28:21 +00001675 Info.Param = BaseInfo.Param;
1676 Info.FirstArg = BaseInfo.FirstArg;
1677 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001678 }
1679
1680 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001681 }
Mike Stump11289f42009-09-09 15:08:12 +00001682
Faisal Vali683b0742016-05-19 02:28:21 +00001683 // Visit base classes
1684 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1685 for (const auto &Base : Next->bases()) {
1686 assert(Base.getType()->isRecordType() &&
1687 "Base class that isn't a record?");
1688 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1689 }
1690 }
Mike Stump11289f42009-09-09 15:08:12 +00001691
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001692 if (Successful) {
1693 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001694 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001695 }
Richard Smith9b296e32016-04-25 19:09:05 +00001696
Douglas Gregore81f3e72009-07-07 23:09:34 +00001697 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001698 }
1699
Douglas Gregor637d9982009-06-10 23:47:09 +00001700 // T type::*
1701 // T T::*
1702 // T (type::*)()
1703 // type (T::*)()
1704 // type (type::*)(T)
1705 // type (T::*)(T)
1706 // T (type::*)(T)
1707 // T (T::*)()
1708 // T (T::*)(T)
1709 case Type::MemberPointer: {
1710 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1711 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1712 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001713 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001714
David Majnemera381cda2015-11-30 20:34:28 +00001715 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1716 if (ParamPointeeType->isFunctionType())
1717 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1718 /*IsCtorOrDtor=*/false, Info.getLocation());
1719 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1720 if (ArgPointeeType->isFunctionType())
1721 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1722 /*IsCtorOrDtor=*/false, Info.getLocation());
1723
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001724 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001725 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001726 ParamPointeeType,
1727 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001728 Info, Deduced,
1729 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001730 return Result;
1731
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001732 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1733 QualType(MemPtrParam->getClass(), 0),
1734 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001735 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001736 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001737 }
1738
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001739 // (clang extension)
1740 //
Mike Stump11289f42009-09-09 15:08:12 +00001741 // type(^)(T)
1742 // T(^)()
1743 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001744 case Type::BlockPointer: {
1745 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1746 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001747
Anders Carlssona767eee2009-06-12 16:23:10 +00001748 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001749 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001750
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001751 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1752 BlockPtrParam->getPointeeType(),
1753 BlockPtrArg->getPointeeType(),
1754 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001755 }
1756
Douglas Gregor39c02722011-06-15 16:02:29 +00001757 // (clang extension)
1758 //
1759 // T __attribute__(((ext_vector_type(<integral constant>))))
1760 case Type::ExtVector: {
1761 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1762 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1763 // Make sure that the vectors have the same number of elements.
1764 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1765 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001766
Douglas Gregor39c02722011-06-15 16:02:29 +00001767 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001768 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1769 VectorParam->getElementType(),
1770 VectorArg->getElementType(),
1771 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001772 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001773
1774 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001775 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1776 // We can't check the number of elements, since the argument has a
1777 // dependent number of elements. This can only occur during partial
1778 // ordering.
1779
1780 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001781 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1782 VectorParam->getElementType(),
1783 VectorArg->getElementType(),
1784 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001785 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001786
Douglas Gregor39c02722011-06-15 16:02:29 +00001787 return Sema::TDK_NonDeducedMismatch;
1788 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001789
Douglas Gregor39c02722011-06-15 16:02:29 +00001790 // (clang extension)
1791 //
1792 // T __attribute__(((ext_vector_type(N))))
1793 case Type::DependentSizedExtVector: {
1794 const DependentSizedExtVectorType *VectorParam
1795 = cast<DependentSizedExtVectorType>(Param);
1796
1797 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1798 // Perform deduction on the element types.
1799 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001800 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1801 VectorParam->getElementType(),
1802 VectorArg->getElementType(),
1803 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001804 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001805
Douglas Gregor39c02722011-06-15 16:02:29 +00001806 // Perform deduction on the vector size, if we can.
1807 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001808 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001809 if (!NTTP)
1810 return Sema::TDK_Success;
1811
1812 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1813 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001814 // Note that we use the "array bound" rules here; just like in that
1815 // case, we don't have any particular type for the vector size, but
1816 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001817 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001818 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001819 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001820 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001821
1822 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001823 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1824 // Perform deduction on the element types.
1825 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001826 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1827 VectorParam->getElementType(),
1828 VectorArg->getElementType(),
1829 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001830 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001831
Douglas Gregor39c02722011-06-15 16:02:29 +00001832 // Perform deduction on the vector size, if we can.
1833 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001834 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001835 if (!NTTP)
1836 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001837
Richard Smith5f274382016-09-28 23:55:27 +00001838 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1839 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001840 Info, Deduced);
1841 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001842
Douglas Gregor39c02722011-06-15 16:02:29 +00001843 return Sema::TDK_NonDeducedMismatch;
1844 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001845
Douglas Gregor637d9982009-06-10 23:47:09 +00001846 case Type::TypeOfExpr:
1847 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001848 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001849 case Type::UnresolvedUsing:
1850 case Type::Decltype:
1851 case Type::UnaryTransform:
1852 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001853 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001854 case Type::DependentTemplateSpecialization:
1855 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001856 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001857 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001858 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001859 }
1860
David Blaikiee4d798f2012-01-20 21:50:17 +00001861 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001862}
1863
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001864static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001865DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001866 TemplateParameterList *TemplateParams,
1867 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001868 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001869 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001870 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001871 // If the template argument is a pack expansion, perform template argument
1872 // deduction against the pattern of that expansion. This only occurs during
1873 // partial ordering.
1874 if (Arg.isPackExpansion())
1875 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001877 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001878 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001879 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001880
1881 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001882 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001883 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1884 Param.getAsType(),
1885 Arg.getAsType(),
1886 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001887 Info.FirstArg = Param;
1888 Info.SecondArg = Arg;
1889 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001890
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001891 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001892 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001894 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001895 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001896 Info.FirstArg = Param;
1897 Info.SecondArg = Arg;
1898 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001899
1900 case TemplateArgument::TemplateExpansion:
1901 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001902
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001903 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001904 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001905 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001906 return Sema::TDK_Success;
1907
1908 Info.FirstArg = Param;
1909 Info.SecondArg = Arg;
1910 return Sema::TDK_NonDeducedMismatch;
1911
1912 case TemplateArgument::NullPtr:
1913 if (Arg.getKind() == TemplateArgument::NullPtr &&
1914 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001915 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001916
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001917 Info.FirstArg = Param;
1918 Info.SecondArg = Arg;
1919 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001920
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001921 case TemplateArgument::Integral:
1922 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001923 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001924 return Sema::TDK_Success;
1925
1926 Info.FirstArg = Param;
1927 Info.SecondArg = Arg;
1928 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001929 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001930
1931 if (Arg.getKind() == TemplateArgument::Expression) {
1932 Info.FirstArg = Param;
1933 Info.SecondArg = Arg;
1934 return Sema::TDK_NonDeducedMismatch;
1935 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001936
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001937 Info.FirstArg = Param;
1938 Info.SecondArg = Arg;
1939 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001940
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001941 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001942 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001943 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001944 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001945 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001946 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001947 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001948 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001949 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001950 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001951 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1952 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001953 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001954 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001955 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1956 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001957 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001958 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1959 Arg.getAsDecl(),
1960 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001961 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001963 Info.FirstArg = Param;
1964 Info.SecondArg = Arg;
1965 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001968 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001969 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001970 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001971 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001972 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001973 }
Mike Stump11289f42009-09-09 15:08:12 +00001974
David Blaikiee4d798f2012-01-20 21:50:17 +00001975 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001976}
1977
Douglas Gregor7baabef2010-12-22 18:17:10 +00001978/// \brief Determine whether there is a template argument to be used for
1979/// deduction.
1980///
1981/// This routine "expands" argument packs in-place, overriding its input
1982/// parameters so that \c Args[ArgIdx] will be the available template argument.
1983///
1984/// \returns true if there is another template argument (which will be at
1985/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001986static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1987 unsigned &ArgIdx) {
1988 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001989 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Douglas Gregor7baabef2010-12-22 18:17:10 +00001991 const TemplateArgument &Arg = Args[ArgIdx];
1992 if (Arg.getKind() != TemplateArgument::Pack)
1993 return true;
1994
Richard Smith0bda5b52016-12-23 23:46:56 +00001995 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1996 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001997 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001998 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001999}
2000
Douglas Gregord0ad2942010-12-23 01:24:45 +00002001/// \brief Determine whether the given set of template arguments has a pack
2002/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002003static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2004 bool FoundPackExpansion = false;
2005 for (const auto &A : Args) {
2006 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002007 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002008
2009 if (A.getKind() == TemplateArgument::Pack)
2010 return hasPackExpansionBeforeEnd(A.pack_elements());
2011
2012 if (A.isPackExpansion())
2013 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregord0ad2942010-12-23 01:24:45 +00002016 return false;
2017}
2018
Douglas Gregor7baabef2010-12-22 18:17:10 +00002019static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002020DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002021 ArrayRef<TemplateArgument> Params,
2022 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002023 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002024 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2025 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002026 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027 // If the template argument list of P contains a pack expansion that is not
2028 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002029 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002030 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002031 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002033 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034 // If P has a form that contains <T> or <i>, then each argument Pi of the
2035 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002036 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002037 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002038 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002039 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002040 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002041
Douglas Gregor7baabef2010-12-22 18:17:10 +00002042 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002043 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002044 return NumberOfArgumentsMustMatch
2045 ? Sema::TDK_MiscellaneousDeductionFailure
2046 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Richard Smith26b86ea2016-12-31 21:41:23 +00002048 // C++1z [temp.deduct.type]p9:
2049 // During partial ordering, if Ai was originally a pack expansion [and]
2050 // Pi is not a pack expansion, template argument deduction fails.
2051 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002052 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002053
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002054 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002055 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002056 = DeduceTemplateArguments(S, TemplateParams,
2057 Params[ParamIdx], Args[ArgIdx],
2058 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059 return Result;
2060
Douglas Gregor7baabef2010-12-22 18:17:10 +00002061 // Move to the next argument.
2062 ++ArgIdx;
2063 continue;
2064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002066 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002068 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069 // If Pi is a pack expansion, then the pattern of Pi is compared with
2070 // each remaining argument in the template argument list of A. Each
2071 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002072 // template parameter packs expanded by Pi.
2073 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002075 // FIXME: If there are no remaining arguments, we can bail out early
2076 // and set any deduced parameter packs to an empty argument pack.
2077 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Richard Smith0a80d572014-05-29 01:12:14 +00002079 // Prepare to deduce the packs within the pattern.
2080 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002081
2082 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002084 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00002085 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002086 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002088 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2089 Info, Deduced))
2090 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091
Richard Smith0a80d572014-05-29 01:12:14 +00002092 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002095 // Build argument packs for each of the parameter packs expanded by this
2096 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002097 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
Douglas Gregor7baabef2010-12-22 18:17:10 +00002101 return Sema::TDK_Success;
2102}
2103
Mike Stump11289f42009-09-09 15:08:12 +00002104static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002105DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002106 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002107 const TemplateArgumentList &ParamList,
2108 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002109 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002110 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002111 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002112 ArgList.asArray(), Info, Deduced,
2113 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002114}
2115
Douglas Gregor705c9002009-06-26 20:57:09 +00002116/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002117static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002118 TemplateArgument X,
2119 const TemplateArgument &Y,
2120 bool PackExpansionMatchesPack = false) {
2121 // If we're checking deduced arguments (X) against original arguments (Y),
2122 // we will have flattened packs to non-expansions in X.
2123 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2124 X = X.getPackExpansionPattern();
2125
Douglas Gregor705c9002009-06-26 20:57:09 +00002126 if (X.getKind() != Y.getKind())
2127 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregor705c9002009-06-26 20:57:09 +00002129 switch (X.getKind()) {
2130 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002131 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregor705c9002009-06-26 20:57:09 +00002133 case TemplateArgument::Type:
2134 return Context.getCanonicalType(X.getAsType()) ==
2135 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002136
Douglas Gregor705c9002009-06-26 20:57:09 +00002137 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002138 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002139
2140 case TemplateArgument::NullPtr:
2141 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002142
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002143 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002144 case TemplateArgument::TemplateExpansion:
2145 return Context.getCanonicalTemplateName(
2146 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2147 Context.getCanonicalTemplateName(
2148 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002149
Douglas Gregor705c9002009-06-26 20:57:09 +00002150 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002151 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002153 case TemplateArgument::Expression: {
2154 llvm::FoldingSetNodeID XID, YID;
2155 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002157 return XID == YID;
2158 }
Mike Stump11289f42009-09-09 15:08:12 +00002159
Douglas Gregor705c9002009-06-26 20:57:09 +00002160 case TemplateArgument::Pack:
2161 if (X.pack_size() != Y.pack_size())
2162 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002163
2164 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2165 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002166 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002167 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002168 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002169 return false;
2170
2171 return true;
2172 }
2173
David Blaikiee4d798f2012-01-20 21:50:17 +00002174 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002175}
2176
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177/// \brief Allocate a TemplateArgumentLoc where all locations have
2178/// been initialized to the given location.
2179///
James Dennett634962f2012-06-14 21:40:34 +00002180/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002181/// location information for.
2182///
2183/// \param NTTPType For a declaration template argument, the type of
2184/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002185/// argument. Can be null if no type sugar is available to add to the
2186/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002187///
2188/// \param Loc The source location to use for the resulting template
2189/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002190TemplateArgumentLoc
2191Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2192 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002193 switch (Arg.getKind()) {
2194 case TemplateArgument::Null:
2195 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregorca4686d2011-01-04 23:35:54 +00002197 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002198 return TemplateArgumentLoc(
2199 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200
Douglas Gregorca4686d2011-01-04 23:35:54 +00002201 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002202 if (NTTPType.isNull())
2203 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002204 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2205 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002206 return TemplateArgumentLoc(TemplateArgument(E), E);
2207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208
Eli Friedmanb826a002012-09-26 02:36:12 +00002209 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002210 if (NTTPType.isNull())
2211 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002212 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2213 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002214 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2215 E);
2216 }
2217
Douglas Gregorca4686d2011-01-04 23:35:54 +00002218 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002219 Expr *E =
2220 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002221 return TemplateArgumentLoc(TemplateArgument(E), E);
2222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002223
Douglas Gregor9d802122011-03-02 17:09:35 +00002224 case TemplateArgument::Template:
2225 case TemplateArgument::TemplateExpansion: {
2226 NestedNameSpecifierLocBuilder Builder;
2227 TemplateName Template = Arg.getAsTemplate();
2228 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002229 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002230 else if (QualifiedTemplateName *QTN =
2231 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002232 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002233
Douglas Gregor9d802122011-03-02 17:09:35 +00002234 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002235 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002236 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002237
2238 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002239 Loc, Loc);
2240 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002241
Douglas Gregorca4686d2011-01-04 23:35:54 +00002242 case TemplateArgument::Expression:
2243 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244
Douglas Gregorca4686d2011-01-04 23:35:54 +00002245 case TemplateArgument::Pack:
2246 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248
David Blaikiee4d798f2012-01-20 21:50:17 +00002249 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002250}
2251
2252
2253/// \brief Convert the given deduced template argument and add it to the set of
2254/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002255static bool
2256ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2257 DeducedTemplateArgument Arg,
2258 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002259 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002260 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002261 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002262 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2263 unsigned ArgumentPackIndex) {
2264 // Convert the deduced template argument into a template
2265 // argument that we can check, almost as if the user had written
2266 // the template argument explicitly.
2267 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002268 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002269
2270 // Check the template argument, converting it as necessary.
2271 return S.CheckTemplateArgument(
2272 Param, ArgLoc, Template, Template->getLocation(),
2273 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002274 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002275 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2276 : Sema::CTAK_Deduced)
2277 : Sema::CTAK_Specified);
2278 };
2279
Douglas Gregorca4686d2011-01-04 23:35:54 +00002280 if (Arg.getKind() == TemplateArgument::Pack) {
2281 // This is a template argument pack, so check each of its arguments against
2282 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002283 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002284 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002285 // When converting the deduced template argument, append it to the
2286 // general output list. We need to do this so that the template argument
2287 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002288 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002289 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002290 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2291 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002292 if (P.isNull()) {
2293 // We deduced arguments for some elements of this pack, but not for
2294 // all of them. This happens if we get a conditionally-non-deduced
2295 // context in a pack expansion (such as an overload set in one of the
2296 // arguments).
2297 S.Diag(Param->getLocation(),
2298 diag::err_template_arg_deduced_incomplete_pack)
2299 << Arg << Param;
2300 return true;
2301 }
Richard Smith37acb792016-02-03 20:15:01 +00002302 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002303 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
Douglas Gregor51bc5712011-01-05 20:52:18 +00002305 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002306 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
Richard Smithdf18ee92016-02-03 20:40:30 +00002309 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002310 // itself, in case that substitution fails.
2311 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002312 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002313 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002314 MultiLevelTemplateArgumentList Args(TemplateArgs);
2315
2316 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2317 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2318 NTTP, Output,
2319 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002320 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002321 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2322 NTTP->getDeclName()).isNull())
2323 return true;
2324 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2325 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2326 TTP, Output,
2327 Template->getSourceRange());
2328 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2329 return true;
2330 }
2331 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002332 }
Richard Smith37acb792016-02-03 20:15:01 +00002333
Douglas Gregorca4686d2011-01-04 23:35:54 +00002334 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002335 Output.push_back(
2336 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002337 return false;
2338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002339
Richard Smith37acb792016-02-03 20:15:01 +00002340 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002341}
2342
Richard Smith1f5be4d2016-12-21 01:10:31 +00002343// FIXME: This should not be a template, but
2344// ClassTemplatePartialSpecializationDecl sadly does not derive from
2345// TemplateDecl.
2346template<typename TemplateDeclT>
2347static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002348 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002349 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2350 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2351 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002352 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002353 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2354
2355 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2356 NamedDecl *Param = TemplateParams->getParam(I);
2357
2358 if (!Deduced[I].isNull()) {
2359 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002360 // We may have had explicitly-specified template arguments for a
2361 // template parameter pack (that may or may not have been extended
2362 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002363 if (Param->isParameterPack() && CurrentInstantiationScope &&
2364 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2365 // Forget the partially-substituted pack; its substitution is now
2366 // complete.
2367 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2368 // We still need to check the argument in case it was extended by
2369 // deduction.
2370 } else {
2371 // We have already fully type-checked and converted this
2372 // argument, because it was explicitly-specified. Just record the
2373 // presence of this argument.
2374 Builder.push_back(Deduced[I]);
2375 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002376 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002377 }
2378
Richard Smith9c0c9862017-01-05 20:27:28 +00002379 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002380 // checked and converted.
2381 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002382 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002383 Info.Param = makeTemplateParameter(Param);
2384 // FIXME: These template arguments are temporary. Free them!
2385 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2386 return Sema::TDK_SubstitutionFailure;
2387 }
2388
2389 continue;
2390 }
2391
2392 // C++0x [temp.arg.explicit]p3:
2393 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2394 // be deduced to an empty sequence of template arguments.
2395 // FIXME: Where did the word "trailing" come from?
2396 if (Param->isTemplateParameterPack()) {
2397 // We may have had explicitly-specified template arguments for this
2398 // template parameter pack. If so, our empty deduction extends the
2399 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2400 const TemplateArgument *ExplicitArgs;
2401 unsigned NumExplicitArgs;
2402 if (CurrentInstantiationScope &&
2403 CurrentInstantiationScope->getPartiallySubstitutedPack(
2404 &ExplicitArgs, &NumExplicitArgs) == Param) {
2405 Builder.push_back(TemplateArgument(
2406 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2407
2408 // Forget the partially-substituted pack; its substitution is now
2409 // complete.
2410 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2411 } else {
2412 // Go through the motions of checking the empty argument pack against
2413 // the parameter pack.
2414 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002415 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2416 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002417 Info.Param = makeTemplateParameter(Param);
2418 // FIXME: These template arguments are temporary. Free them!
2419 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2420 return Sema::TDK_SubstitutionFailure;
2421 }
2422 }
2423 continue;
2424 }
2425
2426 // Substitute into the default template argument, if available.
2427 bool HasDefaultArg = false;
2428 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2429 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002430 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2431 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002432 return Sema::TDK_Incomplete;
2433 }
2434
2435 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2436 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2437 HasDefaultArg);
2438
2439 // If there was no default argument, deduction is incomplete.
2440 if (DefArg.getArgument().isNull()) {
2441 Info.Param = makeTemplateParameter(
2442 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2443 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002444 if (PartialOverloading) break;
2445
Richard Smith1f5be4d2016-12-21 01:10:31 +00002446 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2447 : Sema::TDK_Incomplete;
2448 }
2449
2450 // Check whether we can actually use the default argument.
2451 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2452 TD->getSourceRange().getEnd(), 0, Builder,
2453 Sema::CTAK_Specified)) {
2454 Info.Param = makeTemplateParameter(
2455 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2456 // FIXME: These template arguments are temporary. Free them!
2457 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2458 return Sema::TDK_SubstitutionFailure;
2459 }
2460
2461 // If we get here, we successfully used the default template argument.
2462 }
2463
2464 return Sema::TDK_Success;
2465}
2466
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002467static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002468 if (auto *DC = dyn_cast<DeclContext>(D))
2469 return DC;
2470 return D->getDeclContext();
2471}
2472
2473template<typename T> struct IsPartialSpecialization {
2474 static constexpr bool value = false;
2475};
2476template<>
2477struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2478 static constexpr bool value = true;
2479};
2480template<>
2481struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2482 static constexpr bool value = true;
2483};
2484
2485/// Complete template argument deduction for a partial specialization.
2486template <typename T>
2487static typename std::enable_if<IsPartialSpecialization<T>::value,
2488 Sema::TemplateDeductionResult>::type
2489FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002490 Sema &S, T *Partial, bool IsPartialOrdering,
2491 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002492 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2493 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002494 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002495 EnterExpressionEvaluationContext Unevaluated(
2496 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002497 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002498
Richard Smith0da6dc42016-12-24 16:40:51 +00002499 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002500
2501 // C++ [temp.deduct.type]p2:
2502 // [...] or if any template argument remains neither deduced nor
2503 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002504 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002505 if (auto Result = ConvertDeducedTemplateArguments(
2506 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002507 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002508
Douglas Gregor684268d2010-04-29 06:21:43 +00002509 // Form the template argument list from the deduced template arguments.
2510 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002511 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002512
Douglas Gregor684268d2010-04-29 06:21:43 +00002513 Info.reset(DeducedArgumentList);
2514
2515 // Substitute the deduced template arguments into the template
2516 // arguments of the class template partial specialization, and
2517 // verify that the instantiated template arguments are both valid
2518 // and are equivalent to the template arguments originally provided
2519 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002520 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002521 auto *Template = Partial->getSpecializedTemplate();
2522 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2523 Partial->getTemplateArgsAsWritten();
2524 const TemplateArgumentLoc *PartialTemplateArgs =
2525 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002526
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002527 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2528 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002529
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002530 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002531 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2532 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2533 if (ParamIdx >= Partial->getTemplateParameters()->size())
2534 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2535
Richard Smith0da6dc42016-12-24 16:40:51 +00002536 Decl *Param = const_cast<NamedDecl *>(
2537 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002538 Info.Param = makeTemplateParameter(Param);
2539 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2540 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002541 }
2542
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002543 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002544 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2545 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002546 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547
Richard Smith0da6dc42016-12-24 16:40:51 +00002548 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002549 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002550 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002551 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002552 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002553 Info.FirstArg = TemplateArgs[I];
2554 Info.SecondArg = InstArg;
2555 return Sema::TDK_NonDeducedMismatch;
2556 }
2557 }
2558
2559 if (Trap.hasErrorOccurred())
2560 return Sema::TDK_SubstitutionFailure;
2561
2562 return Sema::TDK_Success;
2563}
2564
Richard Smith0e617ec2016-12-27 07:56:27 +00002565/// Complete template argument deduction for a class or variable template,
2566/// when partial ordering against a partial specialization.
2567// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002568static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002569 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2570 const TemplateArgumentList &TemplateArgs,
2571 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2572 TemplateDeductionInfo &Info) {
2573 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002574 EnterExpressionEvaluationContext Unevaluated(
2575 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002576 Sema::SFINAETrap Trap(S);
2577
2578 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2579
2580 // C++ [temp.deduct.type]p2:
2581 // [...] or if any template argument remains neither deduced nor
2582 // explicitly specified, template argument deduction fails.
2583 SmallVector<TemplateArgument, 4> Builder;
2584 if (auto Result = ConvertDeducedTemplateArguments(
2585 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2586 return Result;
2587
2588 // Check that we produced the correct argument list.
2589 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2590 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2591 TemplateArgument InstArg = Builder[I];
2592 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2593 /*PackExpansionMatchesPack*/true)) {
2594 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2595 Info.FirstArg = TemplateArgs[I];
2596 Info.SecondArg = InstArg;
2597 return Sema::TDK_NonDeducedMismatch;
2598 }
2599 }
2600
2601 if (Trap.hasErrorOccurred())
2602 return Sema::TDK_SubstitutionFailure;
2603
2604 return Sema::TDK_Success;
2605}
2606
2607
Douglas Gregor170bc422009-06-12 22:31:52 +00002608/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002609/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002610/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002611Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002612Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002613 const TemplateArgumentList &TemplateArgs,
2614 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002615 if (Partial->isInvalidDecl())
2616 return TDK_Invalid;
2617
Douglas Gregor170bc422009-06-12 22:31:52 +00002618 // C++ [temp.class.spec.match]p2:
2619 // A partial specialization matches a given actual template
2620 // argument list if the template arguments of the partial
2621 // specialization can be deduced from the actual template argument
2622 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002623
2624 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002625 EnterExpressionEvaluationContext Unevaluated(
2626 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002627 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002628
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002629 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002630 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002631 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002632 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002633 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002634 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002635 TemplateArgs, Info, Deduced))
2636 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002637
Richard Smith80934652012-07-16 01:09:10 +00002638 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002639 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2640 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002641 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002642 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002643
Douglas Gregore1416332009-06-14 08:02:22 +00002644 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002645 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646
Richard Smith87d263e2016-12-25 08:05:23 +00002647 return ::FinishTemplateArgumentDeduction(
2648 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002649}
Douglas Gregor91772d12009-06-13 00:26:55 +00002650
Larisse Voufo39a1e502013-08-06 01:03:05 +00002651/// \brief Perform template argument deduction to determine whether
2652/// the given template arguments match the given variable template
2653/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002654Sema::TemplateDeductionResult
2655Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2656 const TemplateArgumentList &TemplateArgs,
2657 TemplateDeductionInfo &Info) {
2658 if (Partial->isInvalidDecl())
2659 return TDK_Invalid;
2660
2661 // C++ [temp.class.spec.match]p2:
2662 // A partial specialization matches a given actual template
2663 // argument list if the template arguments of the partial
2664 // specialization can be deduced from the actual template argument
2665 // list (14.8.2).
2666
2667 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002668 EnterExpressionEvaluationContext Unevaluated(
2669 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002670 SFINAETrap Trap(*this);
2671
2672 SmallVector<DeducedTemplateArgument, 4> Deduced;
2673 Deduced.resize(Partial->getTemplateParameters()->size());
2674 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2675 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2676 TemplateArgs, Info, Deduced))
2677 return Result;
2678
2679 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002680 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2681 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002682 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002683 return TDK_InstantiationDepth;
2684
2685 if (Trap.hasErrorOccurred())
2686 return Sema::TDK_SubstitutionFailure;
2687
Richard Smith87d263e2016-12-25 08:05:23 +00002688 return ::FinishTemplateArgumentDeduction(
2689 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002690}
2691
Douglas Gregorfc516c92009-06-26 23:27:24 +00002692/// \brief Determine whether the given type T is a simple-template-id type.
2693static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002694 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002695 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002696 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002697
Richard Smith1363e8f2017-09-07 07:22:36 +00002698 // C++17 [temp.local]p2:
2699 // the injected-class-name [...] is equivalent to the template-name followed
2700 // by the template-arguments of the class template specialization or partial
2701 // specialization enclosed in <>
2702 // ... which means it's equivalent to a simple-template-id.
2703 //
2704 // This only arises during class template argument deduction for a copy
2705 // deduction candidate, where it permits slicing.
2706 if (T->getAs<InjectedClassNameType>())
2707 return true;
2708
Douglas Gregorfc516c92009-06-26 23:27:24 +00002709 return false;
2710}
Douglas Gregor9b146582009-07-08 20:55:45 +00002711
2712/// \brief Substitute the explicitly-provided template arguments into the
2713/// given function template according to C++ [temp.arg.explicit].
2714///
2715/// \param FunctionTemplate the function template into which the explicit
2716/// template arguments will be substituted.
2717///
James Dennett634962f2012-06-14 21:40:34 +00002718/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002719/// arguments.
2720///
Mike Stump11289f42009-09-09 15:08:12 +00002721/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002722/// with the converted and checked explicit template arguments.
2723///
Mike Stump11289f42009-09-09 15:08:12 +00002724/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002725/// parameters.
2726///
2727/// \param FunctionType if non-NULL, the result type of the function template
2728/// will also be instantiated and the pointed-to value will be updated with
2729/// the instantiated function type.
2730///
2731/// \param Info if substitution fails for any reason, this object will be
2732/// populated with more information about the failure.
2733///
2734/// \returns TDK_Success if substitution was successful, or some failure
2735/// condition.
2736Sema::TemplateDeductionResult
2737Sema::SubstituteExplicitTemplateArguments(
2738 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002739 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002740 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2741 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002742 QualType *FunctionType,
2743 TemplateDeductionInfo &Info) {
2744 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2745 TemplateParameterList *TemplateParams
2746 = FunctionTemplate->getTemplateParameters();
2747
John McCall6b51f282009-11-23 01:53:49 +00002748 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002749 // No arguments to substitute; just copy over the parameter types and
2750 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002751 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002752 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor9b146582009-07-08 20:55:45 +00002754 if (FunctionType)
2755 *FunctionType = Function->getType();
2756 return TDK_Success;
2757 }
Mike Stump11289f42009-09-09 15:08:12 +00002758
Eli Friedman77dcc722012-02-08 03:07:05 +00002759 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002760 EnterExpressionEvaluationContext Unevaluated(
2761 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002762 SFINAETrap Trap(*this);
2763
Douglas Gregor9b146582009-07-08 20:55:45 +00002764 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002765 // Template arguments that are present shall be specified in the
2766 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002767 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002768 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002769 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002770
2771 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002772 // explicitly-specified template arguments against this function template,
2773 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002774 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00002775 InstantiatingTemplate Inst(
2776 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2777 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002778 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002779 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002780
Richard Smith11255ec2017-01-18 19:19:22 +00002781 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2782 ExplicitTemplateArgs, true, Builder, false) ||
2783 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002784 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002785 if (Index >= TemplateParams->size())
2786 Index = TemplateParams->size() - 1;
2787 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002788 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002789 }
Mike Stump11289f42009-09-09 15:08:12 +00002790
Douglas Gregor9b146582009-07-08 20:55:45 +00002791 // Form the template argument list from the explicitly-specified
2792 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002793 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002794 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002795 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796
John McCall036855a2010-10-12 19:40:14 +00002797 // Template argument deduction and the final substitution should be
2798 // done in the context of the templated declaration. Explicit
2799 // argument substitution, on the other hand, needs to happen in the
2800 // calling context.
2801 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2802
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002804 // note that the template argument pack is partially substituted and record
2805 // the explicit template arguments. They'll be used as part of deduction
2806 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002807 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2808 const TemplateArgument &Arg = Builder[I];
2809 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002810 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002812 Arg.pack_begin(),
2813 Arg.pack_size());
2814 break;
2815 }
2816 }
2817
Richard Smith5e580292012-02-10 09:58:53 +00002818 const FunctionProtoType *Proto
2819 = Function->getType()->getAs<FunctionProtoType>();
2820 assert(Proto && "Function template does not have a prototype?");
2821
Richard Smith70b13042015-01-09 01:19:56 +00002822 // Isolate our substituted parameters from our caller.
2823 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2824
John McCallc8e321d2016-03-01 02:09:25 +00002825 ExtParameterInfoBuilder ExtParamInfos;
2826
Douglas Gregor9b146582009-07-08 20:55:45 +00002827 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002828 // explicitly-specified template arguments. If the function has a trailing
2829 // return type, substitute it after the arguments to ensure we substitute
2830 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002831 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002832 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002833 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002834 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002835 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002836 return TDK_SubstitutionFailure;
2837 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002838
Richard Smith5e580292012-02-10 09:58:53 +00002839 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002840 QualType ResultType;
2841 {
2842 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002843 // If a declaration declares a member function or member function
2844 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002845 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002846 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002847 // declarator.
2848 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002849 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2851 ThisContext = Method->getParent();
2852 ThisTypeQuals = Method->getTypeQualifiers();
2853 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002854
Douglas Gregor3024f072012-04-16 07:05:22 +00002855 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002856 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002857
2858 ResultType =
2859 SubstType(Proto->getReturnType(),
2860 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2861 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002862 if (ResultType.isNull() || Trap.hasErrorOccurred())
2863 return TDK_SubstitutionFailure;
2864 }
John McCallc8e321d2016-03-01 02:09:25 +00002865
Richard Smith5e580292012-02-10 09:58:53 +00002866 // Instantiate the types of each of the function parameters given the
2867 // explicitly-specified template arguments if we didn't do so earlier.
2868 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002869 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002870 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002871 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002872 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002873 return TDK_SubstitutionFailure;
2874
Douglas Gregor9b146582009-07-08 20:55:45 +00002875 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002876 auto EPI = Proto->getExtProtoInfo();
2877 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00002878
2879 // In C++1z onwards, exception specifications are part of the function type,
2880 // so substitution into the type must also substitute into the exception
2881 // specification.
2882 SmallVector<QualType, 4> ExceptionStorage;
2883 if (getLangOpts().CPlusPlus1z &&
2884 SubstExceptionSpec(
2885 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
2886 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
2887 return TDK_SubstitutionFailure;
2888
Jordan Rose5c382722013-03-08 21:51:21 +00002889 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002890 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002891 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002892 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002893 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2894 return TDK_SubstitutionFailure;
2895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896
Douglas Gregor9b146582009-07-08 20:55:45 +00002897 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002898 // Trailing template arguments that can be deduced (14.8.2) may be
2899 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002900 // template arguments can be deduced, they may all be omitted; in this
2901 // case, the empty template argument list <> itself may also be omitted.
2902 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002903 // Take all of the explicitly-specified arguments and put them into
2904 // the set of deduced template arguments. Explicitly-specified
2905 // parameter packs, however, will be set to NULL since the deduction
2906 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002907 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002908 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2909 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2910 if (Arg.getKind() == TemplateArgument::Pack)
2911 Deduced.push_back(DeducedTemplateArgument());
2912 else
2913 Deduced.push_back(Arg);
2914 }
Mike Stump11289f42009-09-09 15:08:12 +00002915
Douglas Gregor9b146582009-07-08 20:55:45 +00002916 return TDK_Success;
2917}
2918
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002919/// \brief Check whether the deduced argument type for a call to a function
2920/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00002921static Sema::TemplateDeductionResult
2922CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
2923 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002924 QualType DeducedA) {
2925 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002926
Richard Smithb1efc9b2017-08-30 00:44:08 +00002927 auto Failed = [&]() -> Sema::TemplateDeductionResult {
2928 Info.FirstArg = TemplateArgument(DeducedA);
2929 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2930 Info.CallArgIndex = OriginalArg.ArgIdx;
2931 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
2932 : Sema::TDK_DeducedMismatch;
2933 };
2934
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002935 QualType A = OriginalArg.OriginalArgType;
2936 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002937
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002938 // Check for type equality (top-level cv-qualifiers are ignored).
2939 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00002940 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002941
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002942 // Strip off references on the argument types; they aren't needed for
2943 // the following checks.
2944 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2945 DeducedA = DeducedARef->getPointeeType();
2946 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2947 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002948
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002949 // C++ [temp.deduct.call]p4:
2950 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002951 // - If the original P is a reference type, the deduced A (i.e., the
2952 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002953 // the transformed A.
2954 if (const ReferenceType *OriginalParamRef
2955 = OriginalParamType->getAs<ReferenceType>()) {
2956 // We don't want to keep the reference around any more.
2957 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002958
Richard Smith1be59c52016-10-22 01:32:19 +00002959 // FIXME: Resolve core issue (no number yet): if the original P is a
2960 // reference type and the transformed A is function type "noexcept F",
2961 // the deduced A can be F.
2962 QualType Tmp;
2963 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00002964 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00002965
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002966 Qualifiers AQuals = A.getQualifiers();
2967 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002968
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002969 // Under Objective-C++ ARC, the deduced type may have implicitly
2970 // been given strong or (when dealing with a const reference)
2971 // unsafe_unretained lifetime. If so, update the original
2972 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002973 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002974 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2975 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2976 (DeducedAQuals.hasConst() &&
2977 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2978 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002979 }
2980
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002981 if (AQuals == DeducedAQuals) {
2982 // Qualifiers match; there's nothing to do.
2983 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00002984 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002985 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002986 // Qualifiers are compatible, so have the argument type adopt the
2987 // deduced argument type's qualifiers as if we had performed the
2988 // qualification conversion.
2989 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2990 }
2991 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002992
2993 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002994 // type that can be converted to the deduced A via a function pointer
2995 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002996 //
Richard Smith1be59c52016-10-22 01:32:19 +00002997 // Also allow conversions which merely strip __attribute__((noreturn)) from
2998 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002999 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003000 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003001 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003002 (S.IsQualificationConversion(A, DeducedA, false,
3003 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003004 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003005 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003006
Simon Pilgrim728134c2016-08-12 11:43:57 +00003007 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003008 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003009 // [...] Likewise, if P is a pointer to a class of the form
3010 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003011 // derived class pointed to by the deduced A.
3012 if (const PointerType *OriginalParamPtr
3013 = OriginalParamType->getAs<PointerType>()) {
3014 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3015 if (const PointerType *APtr = A->getAs<PointerType>()) {
3016 if (A->getPointeeType()->isRecordType()) {
3017 OriginalParamType = OriginalParamPtr->getPointeeType();
3018 DeducedA = DeducedAPtr->getPointeeType();
3019 A = APtr->getPointeeType();
3020 }
3021 }
3022 }
3023 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003024
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003025 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003026 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003027
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003028 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003029 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003030 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003031
Richard Smithb1efc9b2017-08-30 00:44:08 +00003032 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003033}
3034
Richard Smithc92d2062017-01-05 23:02:44 +00003035/// Find the pack index for a particular parameter index in an instantiation of
3036/// a function template with specific arguments.
3037///
3038/// \return The pack index for whichever pack produced this parameter, or -1
3039/// if this was not produced by a parameter. Intended to be used as the
3040/// ArgumentPackSubstitutionIndex for further substitutions.
3041// FIXME: We should track this in OriginalCallArgs so we don't need to
3042// reconstruct it here.
3043static unsigned getPackIndexForParam(Sema &S,
3044 FunctionTemplateDecl *FunctionTemplate,
3045 const MultiLevelTemplateArgumentList &Args,
3046 unsigned ParamIdx) {
3047 unsigned Idx = 0;
3048 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3049 if (PD->isParameterPack()) {
3050 unsigned NumExpansions =
3051 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3052 if (Idx + NumExpansions > ParamIdx)
3053 return ParamIdx - Idx;
3054 Idx += NumExpansions;
3055 } else {
3056 if (Idx == ParamIdx)
3057 return -1; // Not a pack expansion
3058 ++Idx;
3059 }
3060 }
3061
3062 llvm_unreachable("parameter index would not be produced from template");
3063}
3064
Mike Stump11289f42009-09-09 15:08:12 +00003065/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003066/// checking the deduced template arguments for completeness and forming
3067/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003068///
3069/// \param OriginalCallArgs If non-NULL, the original call arguments against
3070/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003071Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3072 FunctionTemplateDecl *FunctionTemplate,
3073 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3074 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3075 TemplateDeductionInfo &Info,
3076 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3077 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003078 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003079 EnterExpressionEvaluationContext Unevaluated(
3080 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003081 SFINAETrap Trap(*this);
3082
Douglas Gregor9b146582009-07-08 20:55:45 +00003083 // Enter a new template instantiation context while we instantiate the
3084 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003085 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003086 InstantiatingTemplate Inst(
3087 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3088 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003089 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003090 return TDK_InstantiationDepth;
3091
John McCalle23b8712010-04-29 01:18:58 +00003092 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003093
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003094 // C++ [temp.deduct.type]p2:
3095 // [...] or if any template argument remains neither deduced nor
3096 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003097 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003098 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003099 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003100 CurrentInstantiationScope, NumExplicitlySpecified,
3101 PartialOverloading))
3102 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003103
Richard Smith6eedfe72017-01-09 08:01:21 +00003104 // C++ [temp.deduct.call]p10: [DR1391]
3105 // If deduction succeeds for all parameters that contain
3106 // template-parameters that participate in template argument deduction,
3107 // and all template arguments are explicitly specified, deduced, or
3108 // obtained from default template arguments, remaining parameters are then
3109 // compared with the corresponding arguments. For each remaining parameter
3110 // P with a type that was non-dependent before substitution of any
3111 // explicitly-specified template arguments, if the corresponding argument
3112 // A cannot be implicitly converted to P, deduction fails.
3113 if (CheckNonDependent())
3114 return TDK_NonDependentConversionFailure;
3115
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003116 // Form the template argument list from the deduced template arguments.
3117 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003118 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003119 Info.reset(DeducedArgumentList);
3120
Mike Stump11289f42009-09-09 15:08:12 +00003121 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003122 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003123 DeclContext *Owner = FunctionTemplate->getDeclContext();
3124 if (FunctionTemplate->getFriendObjectKind())
3125 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003126 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003127 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003128 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003129 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003130 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003131
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003133 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Mike Stump11289f42009-09-09 15:08:12 +00003135 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003136 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003137 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3138 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003139 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003140
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003141 // There may have been an error that did not prevent us from constructing a
3142 // declaration. Mark the declaration invalid and return with a substitution
3143 // failure.
3144 if (Trap.hasErrorOccurred()) {
3145 Specialization->setInvalidDecl(true);
3146 return TDK_SubstitutionFailure;
3147 }
3148
Douglas Gregore65aacb2011-06-16 16:50:48 +00003149 if (OriginalCallArgs) {
3150 // C++ [temp.deduct.call]p4:
3151 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003152 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003153 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003154 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003155 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3156 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003157
Richard Smithc92d2062017-01-05 23:02:44 +00003158 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003159 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003160 // FIXME: This presumably means a pack ended up smaller than we
3161 // expected while deducing. Should this not result in deduction
3162 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003163 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003164
Richard Smithc92d2062017-01-05 23:02:44 +00003165 QualType DeducedA;
3166 if (!OriginalArg.DecomposedParam) {
3167 // P is one of the function parameters, just look up its substituted
3168 // type.
3169 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3170 } else {
3171 // P is a decomposed element of a parameter corresponding to a
3172 // braced-init-list argument. Substitute back into P to find the
3173 // deduced A.
3174 QualType &CacheEntry =
3175 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3176 if (CacheEntry.isNull()) {
3177 ArgumentPackSubstitutionIndexRAII PackIndex(
3178 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3179 ParamIdx));
3180 CacheEntry =
3181 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3182 Specialization->getTypeSpecStartLoc(),
3183 Specialization->getDeclName());
3184 }
3185 DeducedA = CacheEntry;
3186 }
3187
Richard Smithb1efc9b2017-08-30 00:44:08 +00003188 if (auto TDK =
3189 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3190 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003191 }
3192 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003193
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003194 // If we suppressed any diagnostics while performing template argument
3195 // deduction, and if we haven't already instantiated this declaration,
3196 // keep track of these diagnostics. They'll be emitted if this specialization
3197 // is actually used.
3198 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003199 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003200 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3201 if (Pos == SuppressedDiagnostics.end())
3202 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3203 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003205
Mike Stump11289f42009-09-09 15:08:12 +00003206 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003207}
3208
John McCall8d08b9b2010-08-27 09:08:28 +00003209/// Gets the type of a function for template-argument-deducton
3210/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003211static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003212 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003213 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003214 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003215 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003216 return QualType();
3217
John McCallc1f69982010-02-02 02:21:27 +00003218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003219 if (Method->isInstance()) {
3220 // An instance method that's referenced in a form that doesn't
3221 // look like a member pointer is just invalid.
3222 if (!R.HasFormOfMemberPointer) return QualType();
3223
Richard Smith2a7d4812013-05-04 07:00:32 +00003224 return S.Context.getMemberPointerType(Fn->getType(),
3225 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003226 }
3227
3228 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003229 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003230}
3231
3232/// Apply the deduction rules for overload sets.
3233///
3234/// \return the null type if this argument should be treated as an
3235/// undeduced context
3236static QualType
3237ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003238 Expr *Arg, QualType ParamType,
3239 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240
John McCall8d08b9b2010-08-27 09:08:28 +00003241 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003242
John McCall8d08b9b2010-08-27 09:08:28 +00003243 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003244
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003245 // C++0x [temp.deduct.call]p4
3246 unsigned TDF = 0;
3247 if (ParamWasReference)
3248 TDF |= TDF_ParamWithReferenceType;
3249 if (R.IsAddressOfOperand)
3250 TDF |= TDF_IgnoreQualifiers;
3251
John McCallc1f69982010-02-02 02:21:27 +00003252 // C++0x [temp.deduct.call]p6:
3253 // When P is a function type, pointer to function type, or pointer
3254 // to member function type:
3255
3256 if (!ParamType->isFunctionType() &&
3257 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003258 !ParamType->isMemberFunctionPointerType()) {
3259 if (Ovl->hasExplicitTemplateArgs()) {
3260 // But we can still look for an explicit specialization.
3261 if (FunctionDecl *ExplicitSpec
3262 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003263 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003264 }
John McCallc1f69982010-02-02 02:21:27 +00003265
George Burgess IVcc2f3552016-03-19 21:51:45 +00003266 DeclAccessPair DAP;
3267 if (FunctionDecl *Viable =
3268 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3269 return GetTypeOfFunction(S, R, Viable);
3270
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003271 return QualType();
3272 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003273
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003274 // Gather the explicit template arguments, if any.
3275 TemplateArgumentListInfo ExplicitTemplateArgs;
3276 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003277 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003278 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003279 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3280 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003281 NamedDecl *D = (*I)->getUnderlyingDecl();
3282
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003283 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3284 // - If the argument is an overload set containing one or more
3285 // function templates, the parameter is treated as a
3286 // non-deduced context.
3287 if (!Ovl->hasExplicitTemplateArgs())
3288 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003289
3290 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003291 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003292 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003293 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3294 Specialization, Info))
3295 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003296
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003297 D = Specialization;
3298 }
John McCallc1f69982010-02-02 02:21:27 +00003299
3300 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003301 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003302 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003303
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003304 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003306 ArgType->isFunctionType())
3307 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003308
John McCallc1f69982010-02-02 02:21:27 +00003309 // - If the argument is an overload set (not containing function
3310 // templates), trial argument deduction is attempted using each
3311 // of the members of the set. If deduction succeeds for only one
3312 // of the overload set members, that member is used as the
3313 // argument value for the deduction. If deduction succeeds for
3314 // more than one member of the overload set the parameter is
3315 // treated as a non-deduced context.
3316
3317 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3318 // Type deduction is done independently for each P/A pair, and
3319 // the deduced template argument values are then combined.
3320 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003321 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003322 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003323 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003324 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003325 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3326 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003327 if (Result) continue;
3328 if (!Match.isNull()) return QualType();
3329 Match = ArgType;
3330 }
3331
3332 return Match;
3333}
3334
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003336/// described in C++ [temp.deduct.call].
3337///
3338/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003339/// argument deduction based on this P/A pair because the argument is an
3340/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003341static bool AdjustFunctionParmAndArgTypesForDeduction(
3342 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3343 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003344 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003345 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003346 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003347 if (ParamType.hasQualifiers())
3348 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003349
3350 // [...] If P is a reference type, the type referred to by P is
3351 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003352 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003353 if (ParamRefType)
3354 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003355
Nathan Sidwell96090022015-01-16 15:20:14 +00003356 // Overload sets usually make this parameter an undeduced context,
3357 // but there are sometimes special circumstances. Typically
3358 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003359 if (ArgType == S.Context.OverloadTy) {
3360 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3361 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003362 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003363 if (ArgType.isNull())
3364 return true;
3365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Douglas Gregor7825bf32011-01-06 22:09:01 +00003367 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003368 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003369 if (ArgType->isIncompleteArrayType()) {
3370 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003371 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003372 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003373
Richard Smith32918772017-02-14 00:25:28 +00003374 // C++1z [temp.deduct.call]p3:
3375 // If P is a forwarding reference and the argument is an lvalue, the type
3376 // "lvalue reference to A" is used in place of A for type deduction.
3377 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003378 Arg->isLValue())
3379 ArgType = S.Context.getLValueReferenceType(ArgType);
3380 } else {
3381 // C++ [temp.deduct.call]p2:
3382 // If P is not a reference type:
3383 // - If A is an array type, the pointer type produced by the
3384 // array-to-pointer standard conversion (4.2) is used in place of
3385 // A for type deduction; otherwise,
3386 if (ArgType->isArrayType())
3387 ArgType = S.Context.getArrayDecayedType(ArgType);
3388 // - If A is a function type, the pointer type produced by the
3389 // function-to-pointer standard conversion (4.3) is used in place
3390 // of A for type deduction; otherwise,
3391 else if (ArgType->isFunctionType())
3392 ArgType = S.Context.getPointerType(ArgType);
3393 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003394 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003395 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003396 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003397 }
3398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
Douglas Gregor7825bf32011-01-06 22:09:01 +00003400 // C++0x [temp.deduct.call]p4:
3401 // In general, the deduction process attempts to find template argument
3402 // values that will make the deduced A identical to A (after the type A
3403 // is transformed as described above). [...]
3404 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405
Douglas Gregor7825bf32011-01-06 22:09:01 +00003406 // - If the original P is a reference type, the deduced A (i.e., the
3407 // type referred to by the reference) can be more cv-qualified than
3408 // the transformed A.
3409 if (ParamRefType)
3410 TDF |= TDF_ParamWithReferenceType;
3411 // - The transformed A can be another pointer or pointer to member
3412 // type that can be converted to the deduced A via a qualification
3413 // conversion (4.4).
3414 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3415 ArgType->isObjCObjectPointerType())
3416 TDF |= TDF_IgnoreQualifiers;
3417 // - If P is a class and P has the form simple-template-id, then the
3418 // transformed A can be a derived class of the deduced A. Likewise,
3419 // if P is a pointer to a class of the form simple-template-id, the
3420 // transformed A can be a pointer to a derived class pointed to by
3421 // the deduced A.
3422 if (isSimpleTemplateIdType(ParamType) ||
3423 (isa<PointerType>(ParamType) &&
3424 isSimpleTemplateIdType(
3425 ParamType->getAs<PointerType>()->getPointeeType())))
3426 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregor7825bf32011-01-06 22:09:01 +00003428 return false;
3429}
3430
Richard Smithf0393bf2017-02-16 04:22:56 +00003431static bool
3432hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3433 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003434
Richard Smith707eab62017-01-05 04:08:31 +00003435static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003436 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3437 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003438 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3439 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003440 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003441
3442/// \brief Attempt template argument deduction from an initializer list
3443/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003444static Sema::TemplateDeductionResult DeduceFromInitializerList(
3445 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3446 InitListExpr *ILE, TemplateDeductionInfo &Info,
3447 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003448 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3449 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003450 // C++ [temp.deduct.call]p1: (CWG 1591)
3451 // If removing references and cv-qualifiers from P gives
3452 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3453 // a non-empty initializer list, then deduction is performed instead for
3454 // each element of the initializer list, taking P0 as a function template
3455 // parameter type and the initializer element as its argument
3456 //
Richard Smith707eab62017-01-05 04:08:31 +00003457 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003458 if (!ILE->getNumInits())
3459 return Sema::TDK_Success;
3460
Richard Smitha7d5ec92017-01-04 19:47:19 +00003461 QualType ElTy;
3462 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3463 if (ArrTy)
3464 ElTy = ArrTy->getElementType();
3465 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3466 // Otherwise, an initializer list argument causes the parameter to be
3467 // considered a non-deduced context
3468 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003469 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003470
Faisal Valif6dfdb32015-12-10 05:36:39 +00003471 // Deduction only needs to be done for dependent types.
3472 if (ElTy->isDependentType()) {
3473 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003474 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003475 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003476 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003477 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003478 }
3479 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003480
3481 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3482 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003483 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003484 // Determine the array bound is something we can deduce.
3485 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003486 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003487 // We can perform template argument deduction for the given non-type
3488 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003489 // C++ [temp.deduct.type]p13:
3490 // The type of N in the type T[N] is std::size_t.
3491 QualType T = S.Context.getSizeType();
3492 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003493 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003494 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003495 /*ArrayBound=*/true, Info, Deduced))
3496 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003497 }
3498 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003499
3500 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003501}
3502
Richard Smith707eab62017-01-05 04:08:31 +00003503/// \brief Perform template argument deduction per [temp.deduct.call] for a
3504/// single parameter / argument pair.
3505static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003506 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3507 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003508 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3509 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003510 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003511 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003512 QualType OrigParamType = ParamType;
3513
3514 // If P is a reference type [...]
3515 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003516 if (AdjustFunctionParmAndArgTypesForDeduction(
3517 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003518 return Sema::TDK_Success;
3519
Richard Smith707eab62017-01-05 04:08:31 +00003520 // If [...] the argument is a non-empty initializer list [...]
3521 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3522 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003523 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003524
3525 // [...] the deduction process attempts to find template argument values
3526 // that will make the deduced A identical to A
3527 //
3528 // Keep track of the argument type and corresponding parameter index,
3529 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003530 OriginalCallArgs.push_back(
3531 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003532 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003533 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003534}
3535
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003536/// \brief Perform template argument deduction from a function call
3537/// (C++ [temp.deduct.call]).
3538///
3539/// \param FunctionTemplate the function template for which we are performing
3540/// template argument deduction.
3541///
James Dennett18348b62012-06-22 08:52:37 +00003542/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003543/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003544///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003545/// \param Args the function call arguments
3546///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003547/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003548/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003549/// template argument deduction.
3550///
3551/// \param Info the argument will be updated to provide additional information
3552/// about template argument deduction.
3553///
Richard Smith6eedfe72017-01-09 08:01:21 +00003554/// \param CheckNonDependent A callback to invoke to check conversions for
3555/// non-dependent parameters, between deduction and substitution, per DR1391.
3556/// If this returns true, substitution will be skipped and we return
3557/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3558/// types (after substituting explicit template arguments).
3559///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003560/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003561Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3562 FunctionTemplateDecl *FunctionTemplate,
3563 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003564 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003565 bool PartialOverloading,
3566 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003567 if (FunctionTemplate->isInvalidDecl())
3568 return TDK_Invalid;
3569
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003570 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003571 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003572
Richard Smith32918772017-02-14 00:25:28 +00003573 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3574
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003575 // C++ [temp.deduct.call]p1:
3576 // Template argument deduction is done by comparing each function template
3577 // parameter type (call it P) with the type of the corresponding argument
3578 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003579 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003580 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003581 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003582 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003583 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003584 if (Proto->isTemplateVariadic())
3585 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003586 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003587 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003588 }
Mike Stump11289f42009-09-09 15:08:12 +00003589
Douglas Gregor89026b52009-06-30 23:57:56 +00003590 // The types of the parameters from which we will perform template argument
3591 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003592 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003593 TemplateParameterList *TemplateParams
3594 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003595 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003596 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003597 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003598 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003599 TemplateDeductionResult Result =
3600 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003601 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003602 Deduced,
3603 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003604 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003605 Info);
3606 if (Result)
3607 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003608
3609 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003610 } else {
3611 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003612 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003613 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3614 }
Mike Stump11289f42009-09-09 15:08:12 +00003615
Richard Smith6eedfe72017-01-09 08:01:21 +00003616 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003617
3618 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3619 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003620 // C++ [demp.deduct.call]p1: (DR1391)
3621 // Template argument deduction is done by comparing each function template
3622 // parameter that contains template-parameters that participate in
3623 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003624 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003625 return Sema::TDK_Success;
3626
Richard Smith707eab62017-01-05 04:08:31 +00003627 // ... with the type of the corresponding argument
3628 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003629 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003630 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003631 };
3632
Douglas Gregor89026b52009-06-30 23:57:56 +00003633 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003634 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003635 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003636 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003637 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003638 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003639
Richard Smitha7d5ec92017-01-04 19:47:19 +00003640 const PackExpansionType *ParamExpansion =
3641 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003642 if (!ParamExpansion) {
3643 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003644 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003645 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Richard Smith6eedfe72017-01-09 08:01:21 +00003647 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003648 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003649 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003650
Douglas Gregor7825bf32011-01-06 22:09:01 +00003651 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
Richard Smithde0d34a2017-01-09 07:14:40 +00003654 QualType ParamPattern = ParamExpansion->getPattern();
3655 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3656 ParamPattern);
3657
Douglas Gregor7825bf32011-01-06 22:09:01 +00003658 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659 // For a function parameter pack that occurs at the end of the
3660 // parameter-declaration-list, the type A of each remaining argument of
3661 // the call is compared with the type P of the declarator-id of the
3662 // function parameter pack. Each comparison deduces template arguments
3663 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003664 // the function parameter pack. When a function parameter pack appears
3665 // in a non-deduced context [not at the end of the list], the type of
3666 // that parameter pack is never deduced.
3667 //
3668 // FIXME: The above rule allows the size of the parameter pack to change
3669 // after we skip it (in the non-deduced case). That makes no sense, so
3670 // we instead notionally deduce the pack against N arguments, where N is
3671 // the length of the explicitly-specified pack if it's expanded by the
3672 // parameter pack and 0 otherwise, and we treat each deduction as a
3673 // non-deduced context.
3674 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003675 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3676 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003677 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3678 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003679 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003680 } else {
3681 // If the parameter type contains an explicitly-specified pack that we
3682 // could not expand, skip the number of parameters notionally created
3683 // by the expansion.
3684 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003685 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003686 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003687 ++I, ++ArgIdx) {
3688 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003689 // FIXME: Should we add OriginalCallArgs for these? What if the
3690 // corresponding argument is a list?
3691 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003692 }
3693 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695
Douglas Gregor7825bf32011-01-06 22:09:01 +00003696 // Build argument packs for each of the parameter packs expanded by this
3697 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003698 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003700 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003701
Richard Smith6eedfe72017-01-09 08:01:21 +00003702 return FinishTemplateArgumentDeduction(
3703 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3704 &OriginalCallArgs, PartialOverloading,
3705 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003706}
3707
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003708QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003709 QualType FunctionType,
3710 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003711 if (ArgFunctionType.isNull())
3712 return ArgFunctionType;
3713
3714 const FunctionProtoType *FunctionTypeP =
3715 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003716 const FunctionProtoType *ArgFunctionTypeP =
3717 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003718
3719 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3720 bool Rebuild = false;
3721
3722 CallingConv CC = FunctionTypeP->getCallConv();
3723 if (EPI.ExtInfo.getCC() != CC) {
3724 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3725 Rebuild = true;
3726 }
3727
3728 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3729 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3730 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3731 Rebuild = true;
3732 }
3733
3734 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3735 ArgFunctionTypeP->hasExceptionSpec())) {
3736 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3737 Rebuild = true;
3738 }
3739
3740 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003741 return ArgFunctionType;
3742
Richard Smithbaa47832016-12-01 02:11:49 +00003743 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3744 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003745}
3746
Douglas Gregor9b146582009-07-08 20:55:45 +00003747/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003748/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3749/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003750///
3751/// \param FunctionTemplate the function template for which we are performing
3752/// template argument deduction.
3753///
James Dennett18348b62012-06-22 08:52:37 +00003754/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003755/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003756///
3757/// \param ArgFunctionType the function type that will be used as the
3758/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003759/// function template's function type. This type may be NULL, if there is no
3760/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003761///
3762/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003763/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003764/// template argument deduction.
3765///
3766/// \param Info the argument will be updated to provide additional information
3767/// about template argument deduction.
3768///
Richard Smithbaa47832016-12-01 02:11:49 +00003769/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3770/// the address of a function template per [temp.deduct.funcaddr] and
3771/// [over.over]. If \c false, we are looking up a function template
3772/// specialization based on its signature, per [temp.deduct.decl].
3773///
Douglas Gregor9b146582009-07-08 20:55:45 +00003774/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003775Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3776 FunctionTemplateDecl *FunctionTemplate,
3777 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3778 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3779 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003780 if (FunctionTemplate->isInvalidDecl())
3781 return TDK_Invalid;
3782
Douglas Gregor9b146582009-07-08 20:55:45 +00003783 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3784 TemplateParameterList *TemplateParams
3785 = FunctionTemplate->getTemplateParameters();
3786 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003787
Douglas Gregor9b146582009-07-08 20:55:45 +00003788 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003789 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003791 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003792 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003793 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003794 if (TemplateDeductionResult Result
3795 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003796 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003797 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003798 &FunctionType, Info))
3799 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003800
3801 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003802 }
3803
Richard Smithcd198152017-06-07 21:46:22 +00003804 // When taking the address of a function, we require convertibility of
3805 // the resulting function type. Otherwise, we allow arbitrary mismatches
3806 // of calling convention and noreturn.
3807 if (!IsAddressOfFunction)
3808 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3809 /*AdjustExceptionSpec*/false);
3810
Eli Friedman77dcc722012-02-08 03:07:05 +00003811 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003812 EnterExpressionEvaluationContext Unevaluated(
3813 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003814 SFINAETrap Trap(*this);
3815
John McCallc1f69982010-02-02 02:21:27 +00003816 Deduced.resize(TemplateParams->size());
3817
Richard Smith2a7d4812013-05-04 07:00:32 +00003818 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003819 // type so that we treat it as a non-deduced context in what follows. If we
3820 // are looking up by signature, the signature type should also have a deduced
3821 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003822 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003823 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003824 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003825 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003826 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003827 }
3828
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003829 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00003830 unsigned TDF =
3831 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003832 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003833 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003834 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003835 FunctionType, ArgFunctionType,
3836 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003837 return Result;
3838 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003839
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003841 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3842 NumExplicitlySpecified,
3843 Specialization, Info))
3844 return Result;
3845
Richard Smith2a7d4812013-05-04 07:00:32 +00003846 // If the function has a deduced return type, deduce it now, so we can check
3847 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003848 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003849 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003850 DeduceReturnType(Specialization, Info.getLocation(), false))
3851 return TDK_MiscellaneousDeductionFailure;
3852
Richard Smith9095e5b2016-11-01 01:31:23 +00003853 // If the function has a dependent exception specification, resolve it now,
3854 // so we can check that the exception specification matches.
3855 auto *SpecializationFPT =
3856 Specialization->getType()->castAs<FunctionProtoType>();
3857 if (getLangOpts().CPlusPlus1z &&
3858 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3859 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3860 return TDK_MiscellaneousDeductionFailure;
3861
Richard Smithcd198152017-06-07 21:46:22 +00003862 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00003863 // substituted and resolved type we just formed. (Calling convention and
3864 // noreturn can't be dependent, so we don't actually need this for them
3865 // right now.)
3866 QualType SpecializationType = Specialization->getType();
3867 if (!IsAddressOfFunction)
3868 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3869 /*AdjustExceptionSpec*/true);
3870
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003871 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003872 // specialization with respect to arguments of compatible pointer to function
3873 // types, template argument deduction fails.
3874 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003875 if (IsAddressOfFunction &&
3876 !isSameOrCompatibleFunctionType(
3877 Context.getCanonicalType(SpecializationType),
3878 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003879 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003880
3881 if (!IsAddressOfFunction &&
3882 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003883 return TDK_MiscellaneousDeductionFailure;
3884 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003885
3886 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003887}
3888
Simon Pilgrim728134c2016-08-12 11:43:57 +00003889/// \brief Given a function declaration (e.g. a generic lambda conversion
3890/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003891/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3892/// to replace 'auto' with and not the actual result type you want
3893/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003894static inline void
3895SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003896 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003897 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003898 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003899 assert(AutoResultType->getContainedAutoType());
3900 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003901 TypeToReplaceAutoWith);
3902 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3903}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003904
Simon Pilgrim728134c2016-08-12 11:43:57 +00003905/// \brief Given a specialized conversion operator of a generic lambda
3906/// create the corresponding specializations of the call operator and
3907/// the static-invoker. If the return type of the call operator is auto,
3908/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003909/// return type of the destination function ptr.
3910
Simon Pilgrim728134c2016-08-12 11:43:57 +00003911static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003912SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3913 CXXConversionDecl *ConversionSpecialized,
3914 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3915 QualType ReturnTypeOfDestFunctionPtr,
3916 TemplateDeductionInfo &TDInfo,
3917 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003918
Faisal Vali2b3a3012013-10-24 23:40:02 +00003919 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003920 assert(LambdaClass && LambdaClass->isGenericLambda());
3921
Faisal Vali2b3a3012013-10-24 23:40:02 +00003922 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003923 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003924 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003925 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003926
3927 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003928 CallOpGeneric->getDescribedFunctionTemplate();
3929
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003931 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003932 // generic lambda's call operator.
3933 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003934 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3935 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003936 0, CallOpSpecialized, TDInfo))
3937 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003938
Faisal Vali2b3a3012013-10-24 23:40:02 +00003939 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003940 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3941 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003942 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003943 CallOpSpecialized->getPointOfInstantiation(),
3944 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003945
Faisal Vali2b3a3012013-10-24 23:40:02 +00003946 // Check to see if the return type of the destination ptr-to-function
3947 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003948 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003949 ReturnTypeOfDestFunctionPtr))
3950 return Sema::TDK_NonDeducedMismatch;
3951 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003952 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003953 // specialized our corresponding call operator, we are ready to
3954 // specialize the static invoker with the deduced arguments of our
3955 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003956 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003957 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3958 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3959
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003960#ifndef NDEBUG
3961 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3962#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003963 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003964 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003965 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003966 "If the call operator succeeded so should the invoker!");
3967 // Set the result type to match the corresponding call operator
3968 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003969 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3970 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003971 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003972 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003973 // to substitute into the 'auto' of the invoker and conversion
3974 // function.
3975 // For e.g.
3976 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3977 // We don't want to subst 'int*' into 'auto' to get int**.
3978
Alp Toker314cc812014-01-25 16:55:45 +00003979 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3980 ->getContainedAutoType()
3981 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003982 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3983 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003984 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003985 TypeToReplaceAutoWith, S);
3986 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003987
Faisal Vali2b3a3012013-10-24 23:40:02 +00003988 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003989 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003990 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003991 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003992 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3993 getType().getTypePtr()->castAs<FunctionProtoType>();
3994 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3995 EPI.TypeQuals = 0;
3996 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003997 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003998 return Sema::TDK_Success;
3999}
Douglas Gregor05155d82009-08-21 23:19:43 +00004000/// \brief Deduce template arguments for a templated conversion
4001/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4002/// conversion function template specialization.
4003Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004004Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004005 QualType ToType,
4006 CXXConversionDecl *&Specialization,
4007 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004008 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004009 return TDK_Invalid;
4010
Faisal Vali2b3a3012013-10-24 23:40:02 +00004011 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004012 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4013
Faisal Vali2b3a3012013-10-24 23:40:02 +00004014 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004015
4016 // Canonicalize the types for deduction.
4017 QualType P = Context.getCanonicalType(FromType);
4018 QualType A = Context.getCanonicalType(ToType);
4019
Douglas Gregord99609a2011-03-06 09:03:20 +00004020 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004021 // If P is a reference type, the type referred to by P is used for
4022 // type deduction.
4023 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4024 P = PRef->getPointeeType();
4025
Douglas Gregord99609a2011-03-06 09:03:20 +00004026 // C++0x [temp.deduct.conv]p4:
4027 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004028 // for type deduction.
4029 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00004030 A = ARef->getPointeeType().getUnqualifiedType();
4031 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004032 //
Mike Stump11289f42009-09-09 15:08:12 +00004033 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00004034 else {
4035 assert(!A->isReferenceType() && "Reference types were handled above");
4036
4037 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004038 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004039 // of P for type deduction; otherwise,
4040 if (P->isArrayType())
4041 P = Context.getArrayDecayedType(P);
4042 // - If P is a function type, the pointer type produced by the
4043 // function-to-pointer standard conversion (4.3) is used in
4044 // place of P for type deduction; otherwise,
4045 else if (P->isFunctionType())
4046 P = Context.getPointerType(P);
4047 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004048 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004049 else
4050 P = P.getUnqualifiedType();
4051
Douglas Gregord99609a2011-03-06 09:03:20 +00004052 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004053 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004054 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004055 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004056 A = A.getUnqualifiedType();
4057 }
4058
Eli Friedman77dcc722012-02-08 03:07:05 +00004059 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004060 EnterExpressionEvaluationContext Unevaluated(
4061 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004062 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004063
4064 // C++ [temp.deduct.conv]p1:
4065 // Template argument deduction is done by comparing the return
4066 // type of the template conversion function (call it P) with the
4067 // type that is required as the result of the conversion (call it
4068 // A) as described in 14.8.2.4.
4069 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004070 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004071 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004072 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004073
4074 // C++0x [temp.deduct.conv]p4:
4075 // In general, the deduction process attempts to find template
4076 // argument values that will make the deduced A identical to
4077 // A. However, there are two cases that allow a difference:
4078 unsigned TDF = 0;
4079 // - If the original A is a reference type, A can be more
4080 // cv-qualified than the deduced A (i.e., the type referred to
4081 // by the reference)
4082 if (ToType->isReferenceType())
4083 TDF |= TDF_ParamWithReferenceType;
4084 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004085 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004086 // conversion.
4087 //
4088 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4089 // both P and A are pointers or member pointers. In this case, we
4090 // just ignore cv-qualifiers completely).
4091 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004092 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004093 TDF |= TDF_IgnoreQualifiers;
4094 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004095 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4096 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004097 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004098
4099 // Create an Instantiation Scope for finalizing the operator.
4100 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004101 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004102 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004103 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004104 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004105 ConversionSpecialized, Info);
4106 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4107
4108 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00004109 // to a ptr-to-function, use the deduced arguments from the conversion
4110 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00004111 // e.g., int (*fp)(int) = [](auto a) { return a; };
4112 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00004113
Faisal Vali2b3a3012013-10-24 23:40:02 +00004114 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00004115 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00004116 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00004117 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00004118 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00004119 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00004120 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00004121 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
4122
Simon Pilgrim728134c2016-08-12 11:43:57 +00004123 // Create the corresponding specializations of the call operator and
4124 // the static-invoker; and if the return type is auto,
4125 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00004126 // DestFunctionPtrReturnType.
4127 // For instance:
4128 // auto L = [](auto a) { return f(a); };
4129 // int (*fp)(int) = L;
4130 // char (*fp2)(int) = L; <-- Not OK.
4131
4132 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00004133 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004134 Info, *this);
4135 }
Douglas Gregor05155d82009-08-21 23:19:43 +00004136 return Result;
4137}
4138
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004139/// \brief Deduce template arguments for a function template when there is
4140/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4141///
4142/// \param FunctionTemplate the function template for which we are performing
4143/// template argument deduction.
4144///
James Dennett18348b62012-06-22 08:52:37 +00004145/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004146/// arguments.
4147///
4148/// \param Specialization if template argument deduction was successful,
4149/// this will be set to the function template specialization produced by
4150/// template argument deduction.
4151///
4152/// \param Info the argument will be updated to provide additional information
4153/// about template argument deduction.
4154///
Richard Smithbaa47832016-12-01 02:11:49 +00004155/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4156/// the address of a function template in a context where we do not have a
4157/// target type, per [over.over]. If \c false, we are looking up a function
4158/// template specialization based on its signature, which only happens when
4159/// deducing a function parameter type from an argument that is a template-id
4160/// naming a function template specialization.
4161///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004162/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004163Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4164 FunctionTemplateDecl *FunctionTemplate,
4165 TemplateArgumentListInfo *ExplicitTemplateArgs,
4166 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4167 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004168 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004169 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004170 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004171}
4172
Richard Smith30482bc2011-02-20 03:19:35 +00004173namespace {
Richard Smith60437622017-02-09 19:17:44 +00004174 /// Substitute the 'auto' specifier or deduced template specialization type
4175 /// specifier within a type for a given replacement type.
4176 class SubstituteDeducedTypeTransform :
4177 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004178 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004179 bool UseTypeSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004180 public:
Richard Smith60437622017-02-09 19:17:44 +00004181 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4182 bool UseTypeSugar = true)
4183 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4184 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4185
4186 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4187 assert(isa<TemplateTypeParmType>(Replacement) &&
4188 "unexpected unsugared replacement kind");
4189 QualType Result = Replacement;
4190 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4191 NewTL.setNameLoc(TL.getNameLoc());
4192 return Result;
4193 }
Nico Weberc153d242014-07-28 00:02:09 +00004194
Richard Smith30482bc2011-02-20 03:19:35 +00004195 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4196 // If we're building the type pattern to deduce against, don't wrap the
4197 // substituted type in an AutoType. Certain template deduction rules
4198 // apply only when a template type parameter appears directly (and not if
4199 // the parameter is found through desugaring). For instance:
4200 // auto &&lref = lvalue;
4201 // must transform into "rvalue reference to T" not "rvalue reference to
4202 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004203 //
4204 // FIXME: Is this still necessary?
4205 if (!UseTypeSugar)
4206 return TransformDesugared(TLB, TL);
4207
4208 QualType Result = SemaRef.Context.getAutoType(
4209 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4210 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4211 NewTL.setNameLoc(TL.getNameLoc());
4212 return Result;
4213 }
4214
4215 QualType TransformDeducedTemplateSpecializationType(
4216 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4217 if (!UseTypeSugar)
4218 return TransformDesugared(TLB, TL);
4219
4220 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4221 TL.getTypePtr()->getTemplateName(),
4222 Replacement, Replacement.isNull());
4223 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4224 NewTL.setNameLoc(TL.getNameLoc());
4225 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004226 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004227
4228 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4229 // Lambdas never need to be transformed.
4230 return E;
4231 }
Richard Smith061f1e22013-04-30 21:23:01 +00004232
Richard Smith2a7d4812013-05-04 07:00:32 +00004233 QualType Apply(TypeLoc TL) {
4234 // Create some scratch storage for the transformed type locations.
4235 // FIXME: We're just going to throw this information away. Don't build it.
4236 TypeLocBuilder TLB;
4237 TLB.reserve(TL.getFullDataSize());
4238 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004239 }
Richard Smith30482bc2011-02-20 03:19:35 +00004240 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004241}
Richard Smith30482bc2011-02-20 03:19:35 +00004242
Richard Smith2a7d4812013-05-04 07:00:32 +00004243Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004244Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4245 Optional<unsigned> DependentDeductionDepth) {
4246 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4247 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004248}
4249
Richard Smithb1efc9b2017-08-30 00:44:08 +00004250/// Attempt to produce an informative diagostic explaining why auto deduction
4251/// failed.
4252/// \return \c true if diagnosed, \c false if not.
4253static bool diagnoseAutoDeductionFailure(Sema &S,
4254 Sema::TemplateDeductionResult TDK,
4255 TemplateDeductionInfo &Info,
4256 ArrayRef<SourceRange> Ranges) {
4257 switch (TDK) {
4258 case Sema::TDK_Inconsistent: {
4259 // Inconsistent deduction means we were deducing from an initializer list.
4260 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4261 D << Info.FirstArg << Info.SecondArg;
4262 for (auto R : Ranges)
4263 D << R;
4264 return true;
4265 }
4266
4267 // FIXME: Are there other cases for which a custom diagnostic is more useful
4268 // than the basic "types don't match" diagnostic?
4269
4270 default:
4271 return false;
4272 }
4273}
4274
Richard Smith061f1e22013-04-30 21:23:01 +00004275/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004276///
Richard Smith87d263e2016-12-25 08:05:23 +00004277/// Note that this is done even if the initializer is dependent. (This is
4278/// necessary to support partial ordering of templates using 'auto'.)
4279/// A dependent type will be produced when deducing from a dependent type.
4280///
Richard Smith30482bc2011-02-20 03:19:35 +00004281/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004282/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004283/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004284/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004285/// \param DependentDeductionDepth Set if we should permit deduction in
4286/// dependent cases. This is necessary for template partial ordering with
4287/// 'auto' template parameters. The value specified is the template
4288/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004289Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004290Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4291 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004292 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004293 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4294 if (NonPlaceholder.isInvalid())
4295 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004296 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004297 }
4298
Richard Smith87d263e2016-12-25 08:05:23 +00004299 if (!DependentDeductionDepth &&
4300 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004301 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004302 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004303 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004304 }
4305
Richard Smith87d263e2016-12-25 08:05:23 +00004306 // Find the depth of template parameter to synthesize.
4307 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4308
Richard Smith74aeef52013-04-26 16:15:35 +00004309 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4310 // Since 'decltype(auto)' can only occur at the top of the type, we
4311 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004312 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004313 if (AT->isDecltypeAuto()) {
4314 if (isa<InitListExpr>(Init)) {
4315 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4316 return DAR_FailedAlreadyDiagnosed;
4317 }
4318
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004319 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004320 if (Deduced.isNull())
4321 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004322 // FIXME: Support a non-canonical deduced type for 'auto'.
4323 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004324 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004325 if (Result.isNull())
4326 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004327 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004328 } else if (!getLangOpts().CPlusPlus) {
4329 if (isa<InitListExpr>(Init)) {
4330 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4331 return DAR_FailedAlreadyDiagnosed;
4332 }
Richard Smith74aeef52013-04-26 16:15:35 +00004333 }
4334 }
4335
Richard Smith30482bc2011-02-20 03:19:35 +00004336 SourceLocation Loc = Init->getExprLoc();
4337
4338 LocalInstantiationScope InstScope(*this);
4339
4340 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004341 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4342 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004343 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4344 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004345 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4346 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004347
Richard Smith87d263e2016-12-25 08:05:23 +00004348 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004349 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004350 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004351 assert(!FuncParam.isNull() &&
4352 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004353
4354 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004355 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004356 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004357
Richard Smith87d263e2016-12-25 08:05:23 +00004358 TemplateDeductionInfo Info(Loc, Depth);
4359
4360 // If deduction failed, don't diagnose if the initializer is dependent; it
4361 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004362 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4363 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004364 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004365 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004366 assert(!Result.isNull() && "substituting DependentTy can't fail");
4367 return DAR_Succeeded;
4368 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004369 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4370 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004371 return DAR_Failed;
4372 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004373
Richard Smith707eab62017-01-05 04:08:31 +00004374 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4375
Richard Smith74801c82012-07-08 04:13:07 +00004376 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004377 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004378 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4379 // against that. Such deduction only succeeds if removing cv-qualifiers and
4380 // references results in std::initializer_list<T>.
4381 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4382 return DAR_Failed;
4383
Richard Smithb1efc9b2017-08-30 00:44:08 +00004384 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004385 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004386 Expr *Init = InitList->getInit(i);
4387
4388 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4389 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004390 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4391 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004392 return DeductionFailed(TDK, {DeducedFromInitRange,
4393 Init->getSourceRange()});
4394
4395 if (DeducedFromInitRange.isInvalid() &&
4396 Deduced[0].getKind() != TemplateArgument::Null)
4397 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004398 }
4399 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004400 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4401 Diag(Loc, diag::err_auto_bitfield);
4402 return DAR_FailedAlreadyDiagnosed;
4403 }
4404
Richard Smithb1efc9b2017-08-30 00:44:08 +00004405 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004406 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004407 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004408 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004409 }
Richard Smith30482bc2011-02-20 03:19:35 +00004410
Richard Smith87d263e2016-12-25 08:05:23 +00004411 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004412 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004413 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004414
Eli Friedmane4310952012-11-06 23:56:42 +00004415 QualType DeducedType = Deduced[0].getAsType();
4416
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004417 if (InitList) {
4418 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4419 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004420 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004421 }
4422
Richard Smith60437622017-02-09 19:17:44 +00004423 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004424 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004425 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004426
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004427 // Check that the deduced argument type is compatible with the original
4428 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004429 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004430 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004431 assert((bool)InitList == OriginalArg.DecomposedParam &&
4432 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004433 if (auto TDK =
4434 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004435 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004436 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004437 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004438 }
4439
Sebastian Redl09edce02012-01-23 22:09:39 +00004440 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004441}
4442
Simon Pilgrim728134c2016-08-12 11:43:57 +00004443QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004444 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004445 if (TypeToReplaceAuto->isDependentType())
4446 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004447 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004448 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004449}
4450
Richard Smith60437622017-02-09 19:17:44 +00004451TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4452 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004453 if (TypeToReplaceAuto->isDependentType())
4454 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004455 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004456 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004457}
4458
Richard Smith33c33c32017-02-04 01:28:01 +00004459QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4460 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004461 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4462 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004463 .TransformType(TypeWithAuto);
4464}
4465
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004466void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4467 if (isa<InitListExpr>(Init))
4468 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004469 VDecl->isInitCapture()
4470 ? diag::err_init_capture_deduction_failure_from_init_list
4471 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004472 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4473 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004474 Diag(VDecl->getLocation(),
4475 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4476 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004477 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4478 << Init->getSourceRange();
4479}
4480
Richard Smith2a7d4812013-05-04 07:00:32 +00004481bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4482 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004483 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004484
4485 if (FD->getTemplateInstantiationPattern())
4486 InstantiateFunctionDefinition(Loc, FD);
4487
Alp Toker314cc812014-01-25 16:55:45 +00004488 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004489 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4490 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4491 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4492 }
4493
4494 return StillUndeduced;
4495}
4496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004498static void
4499AddImplicitObjectParameterType(ASTContext &Context,
4500 CXXMethodDecl *Method,
4501 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004502 // C++11 [temp.func.order]p3:
4503 // [...] The new parameter is of type "reference to cv A," where cv are
4504 // the cv-qualifiers of the function template (if any) and A is
4505 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004506 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004507 // The standard doesn't say explicitly, but we pick the appropriate kind of
4508 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004509 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4510 ArgTy = Context.getQualifiedType(ArgTy,
4511 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004512 if (Method->getRefQualifier() == RQ_RValue)
4513 ArgTy = Context.getRValueReferenceType(ArgTy);
4514 else
4515 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004516 ArgTypes.push_back(ArgTy);
4517}
4518
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004519/// \brief Determine whether the function template \p FT1 is at least as
4520/// specialized as \p FT2.
4521static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004522 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004523 FunctionTemplateDecl *FT1,
4524 FunctionTemplateDecl *FT2,
4525 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004526 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004527 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004529 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4530 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004532 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4533 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004534 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004535 Deduced.resize(TemplateParams->size());
4536
4537 // C++0x [temp.deduct.partial]p3:
4538 // The types used to determine the ordering depend on the context in which
4539 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004540 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004541 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004542 switch (TPOC) {
4543 case TPOC_Call: {
4544 // - In the context of a function call, the function parameter types are
4545 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004546 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4547 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004548
Eli Friedman3b5774a2012-09-19 23:27:04 +00004549 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004550 // [...] If only one of the function templates is a non-static
4551 // member, that function template is considered to have a new
4552 // first parameter inserted in its function parameter list. The
4553 // new parameter is of type "reference to cv A," where cv are
4554 // the cv-qualifiers of the function template (if any) and A is
4555 // the class of which the function template is a member.
4556 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004557 // Note that we interpret this to mean "if one of the function
4558 // templates is a non-static member and the other is a non-member";
4559 // otherwise, the ordering rules for static functions against non-static
4560 // functions don't make any sense.
4561 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004562 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4563 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004564 SmallVector<QualType, 4> Args1;
4565
Richard Smithe5b52202013-09-11 00:52:39 +00004566 unsigned NumComparedArguments = NumCallArguments1;
4567
4568 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004569 // Compare 'this' from Method1 against first parameter from Method2.
4570 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4571 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004572 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004573 // Compare 'this' from Method2 against first parameter from Method1.
4574 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004575 }
4576
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004577 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004578 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004579 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004580 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
Douglas Gregorb837ea42011-01-11 17:34:58 +00004582 // C++ [temp.func.order]p5:
4583 // The presence of unused ellipsis and default arguments has no effect on
4584 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004585 if (Args1.size() > NumComparedArguments)
4586 Args1.resize(NumComparedArguments);
4587 if (Args2.size() > NumComparedArguments)
4588 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004589 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4590 Args1.data(), Args1.size(), Info, Deduced,
4591 TDF_None, /*PartialOrdering=*/true))
4592 return false;
4593
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004594 break;
4595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004597 case TPOC_Conversion:
4598 // - In the context of a call to a conversion operator, the return types
4599 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004600 if (DeduceTemplateArgumentsByTypeMatch(
4601 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4602 Info, Deduced, TDF_None,
4603 /*PartialOrdering=*/true))
4604 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004607 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004608 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004609 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004610 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4611 FD2->getType(), FD1->getType(),
4612 Info, Deduced, TDF_None,
4613 /*PartialOrdering=*/true))
4614 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004615 break;
4616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004618 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 // In most cases, all template parameters must have values in order for
4620 // deduction to succeed, but for partial ordering purposes a template
4621 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004622 // types being used for partial ordering. [ Note: a template parameter used
4623 // in a non-deduced context is considered used. -end note]
4624 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4625 for (; ArgIdx != NumArgs; ++ArgIdx)
4626 if (Deduced[ArgIdx].isNull())
4627 break;
4628
Richard Smithf0393bf2017-02-16 04:22:56 +00004629 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4630 // to substitute the deduced arguments back into the template and check that
4631 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004632
Richard Smithf0393bf2017-02-16 04:22:56 +00004633 if (ArgIdx == NumArgs) {
4634 // All template arguments were deduced. FT1 is at least as specialized
4635 // as FT2.
4636 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004637 }
4638
Richard Smithf0393bf2017-02-16 04:22:56 +00004639 // Figure out which template parameters were used.
4640 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4641 switch (TPOC) {
4642 case TPOC_Call:
4643 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4644 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4645 TemplateParams->getDepth(),
4646 UsedParameters);
4647 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Richard Smithf0393bf2017-02-16 04:22:56 +00004649 case TPOC_Conversion:
4650 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4651 TemplateParams->getDepth(), UsedParameters);
4652 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Richard Smithf0393bf2017-02-16 04:22:56 +00004654 case TPOC_Other:
4655 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4656 TemplateParams->getDepth(),
4657 UsedParameters);
4658 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004659 }
4660
Richard Smithf0393bf2017-02-16 04:22:56 +00004661 for (; ArgIdx != NumArgs; ++ArgIdx)
4662 // If this argument had no value deduced but was used in one of the types
4663 // used for partial ordering, then deduction fails.
4664 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4665 return false;
4666
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004667 return true;
4668}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004669
Douglas Gregorcef1a032011-01-16 16:03:23 +00004670/// \brief Determine whether this a function template whose parameter-type-list
4671/// ends with a function parameter pack.
4672static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4673 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4674 unsigned NumParams = Function->getNumParams();
4675 if (NumParams == 0)
4676 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Douglas Gregorcef1a032011-01-16 16:03:23 +00004678 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4679 if (!Last->isParameterPack())
4680 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681
Douglas Gregorcef1a032011-01-16 16:03:23 +00004682 // Make sure that no previous parameter is a parameter pack.
4683 while (--NumParams > 0) {
4684 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4685 return false;
4686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687
Douglas Gregorcef1a032011-01-16 16:03:23 +00004688 return true;
4689}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004690
Douglas Gregorbe999392009-09-15 16:23:51 +00004691/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004692/// to the rules of function template partial ordering (C++ [temp.func.order]).
4693///
4694/// \param FT1 the first function template
4695///
4696/// \param FT2 the second function template
4697///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004698/// \param TPOC the context in which we are performing partial ordering of
4699/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004700///
Richard Smithe5b52202013-09-11 00:52:39 +00004701/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4702/// only when \c TPOC is \c TPOC_Call.
4703///
4704/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4705/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004706///
Douglas Gregorbe999392009-09-15 16:23:51 +00004707/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004708/// template is more specialized, returns NULL.
4709FunctionTemplateDecl *
4710Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4711 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004712 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004713 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004714 unsigned NumCallArguments1,
4715 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004717 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004719 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004721 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004722 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004724 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004726
Douglas Gregorcef1a032011-01-16 16:03:23 +00004727 // FIXME: This mimics what GCC implements, but doesn't match up with the
4728 // proposed resolution for core issue 692. This area needs to be sorted out,
4729 // but for now we attempt to maintain compatibility.
4730 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4731 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4732 if (Variadic1 != Variadic2)
4733 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Craig Topperc3ec1492014-05-26 06:22:03 +00004735 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004736}
Douglas Gregor9b146582009-07-08 20:55:45 +00004737
Douglas Gregor450f00842009-09-25 18:43:00 +00004738/// \brief Determine if the two templates are equivalent.
4739static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4740 if (T1 == T2)
4741 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742
Douglas Gregor450f00842009-09-25 18:43:00 +00004743 if (!T1 || !T2)
4744 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745
Douglas Gregor450f00842009-09-25 18:43:00 +00004746 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4747}
4748
4749/// \brief Retrieve the most specialized of the given function template
4750/// specializations.
4751///
John McCall58cc69d2010-01-27 01:50:18 +00004752/// \param SpecBegin the start iterator of the function template
4753/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004754///
John McCall58cc69d2010-01-27 01:50:18 +00004755/// \param SpecEnd the end iterator of the function template
4756/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004757///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004759/// diagnostic should occur.
4760///
4761/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4762/// no matching candidates.
4763///
4764/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4765/// occurs.
4766///
4767/// \param CandidateDiag partial diagnostic used for each function template
4768/// specialization that is a candidate in the ambiguous ordering. One parameter
4769/// in this diagnostic should be unbound, which will correspond to the string
4770/// describing the template arguments for the function template specialization.
4771///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004773/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004774UnresolvedSetIterator Sema::getMostSpecialized(
4775 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4776 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004777 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4778 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4779 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004780 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004781 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004782 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004783 FailedCandidates.NoteCandidates(*this, Loc);
4784 }
John McCall58cc69d2010-01-27 01:50:18 +00004785 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787
4788 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004789 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790
Douglas Gregor450f00842009-09-25 18:43:00 +00004791 // Find the function template that is better than all of the templates it
4792 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004793 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004795 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004796 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004797 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4798 FunctionTemplateDecl *Challenger
4799 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004800 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004801 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004802 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004803 Challenger)) {
4804 Best = I;
4805 BestTemplate = Challenger;
4806 }
4807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
Douglas Gregor450f00842009-09-25 18:43:00 +00004809 // Make sure that the "best" function template is more specialized than all
4810 // of the others.
4811 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004812 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4813 FunctionTemplateDecl *Challenger
4814 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004815 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004817 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004818 BestTemplate)) {
4819 Ambiguous = true;
4820 break;
4821 }
4822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor450f00842009-09-25 18:43:00 +00004824 if (!Ambiguous) {
4825 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004826 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828
Douglas Gregor450f00842009-09-25 18:43:00 +00004829 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004830 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004831 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Richard Smithb875c432013-05-04 01:51:08 +00004833 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004834 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4835 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004836 const auto *FD = cast<FunctionDecl>(*I);
4837 PD << FD << getTemplateArgumentBindingsText(
4838 FD->getPrimaryTemplate()->getTemplateParameters(),
4839 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004840 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004841 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004842 Diag((*I)->getLocation(), PD);
4843 }
Richard Smithb875c432013-05-04 01:51:08 +00004844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
John McCall58cc69d2010-01-27 01:50:18 +00004846 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004847}
4848
Richard Smith0da6dc42016-12-24 16:40:51 +00004849/// Determine whether one partial specialization, P1, is at least as
4850/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004851///
Richard Smith26b86ea2016-12-31 21:41:23 +00004852/// \tparam TemplateLikeDecl The kind of P2, which must be a
4853/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004854/// \param T1 The injected-class-name of P1 (faked for a variable template).
4855/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004856template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004857static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004858 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004859 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004860 // C++ [temp.class.order]p1:
4861 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862 // specialized as the second if, given the following rewrite to two
4863 // function templates, the first function template is at least as
4864 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004865 // templates (14.6.6.2):
4866 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867 // first partial specialization and has a single function parameter
4868 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004869 // arguments of the first partial specialization, and
4870 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871 // second partial specialization and has a single function parameter
4872 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004873 // arguments of the second partial specialization.
4874 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004875 // Rather than synthesize function templates, we merely perform the
4876 // equivalent partial ordering by performing deduction directly on
4877 // the template arguments of the class template partial
4878 // specializations. This computation is slightly simpler than the
4879 // general problem of function template partial ordering, because
4880 // class template partial specializations are more constrained. We
4881 // know that every template parameter is deducible from the class
4882 // template partial specialization's template arguments, for
4883 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004884 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004885
Richard Smith0da6dc42016-12-24 16:40:51 +00004886 // Determine whether P1 is at least as specialized as P2.
4887 Deduced.resize(P2->getTemplateParameters()->size());
4888 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4889 T2, T1, Info, Deduced, TDF_None,
4890 /*PartialOrdering=*/true))
4891 return false;
4892
4893 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4894 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004895 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4896 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004897 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4898 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004899 S, P2, /*PartialOrdering=*/true,
4900 TemplateArgumentList(TemplateArgumentList::OnStack,
4901 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004902 Deduced, Info))
4903 return false;
4904
4905 return true;
4906}
4907
4908/// \brief Returns the more specialized class template partial specialization
4909/// according to the rules of partial ordering of class template partial
4910/// specializations (C++ [temp.class.order]).
4911///
4912/// \param PS1 the first class template partial specialization
4913///
4914/// \param PS2 the second class template partial specialization
4915///
4916/// \returns the more specialized class template partial specialization. If
4917/// neither partial specialization is more specialized, returns NULL.
4918ClassTemplatePartialSpecializationDecl *
4919Sema::getMoreSpecializedPartialSpecialization(
4920 ClassTemplatePartialSpecializationDecl *PS1,
4921 ClassTemplatePartialSpecializationDecl *PS2,
4922 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004923 QualType PT1 = PS1->getInjectedSpecializationType();
4924 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Richard Smith0e617ec2016-12-27 07:56:27 +00004926 TemplateDeductionInfo Info(Loc);
4927 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4928 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004929
4930 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004931 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004932
4933 return Better1 ? PS1 : PS2;
4934}
4935
Richard Smith0e617ec2016-12-27 07:56:27 +00004936bool Sema::isMoreSpecializedThanPrimary(
4937 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4938 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4939 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4940 QualType PartialT = Spec->getInjectedSpecializationType();
4941 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4942 return false;
4943 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4944 Info.clearSFINAEDiagnostic();
4945 return false;
4946 }
4947 return true;
4948}
4949
Larisse Voufo39a1e502013-08-06 01:03:05 +00004950VarTemplatePartialSpecializationDecl *
4951Sema::getMoreSpecializedPartialSpecialization(
4952 VarTemplatePartialSpecializationDecl *PS1,
4953 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004954 // Pretend the variable template specializations are class template
4955 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004956 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004957 "the partial specializations being compared should specialize"
4958 " the same template.");
4959 TemplateName Name(PS1->getSpecializedTemplate());
4960 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4961 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004962 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004963 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004964 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004965
Richard Smith0e617ec2016-12-27 07:56:27 +00004966 TemplateDeductionInfo Info(Loc);
4967 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4968 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregorbe999392009-09-15 16:23:51 +00004970 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004971 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972
Richard Smith0da6dc42016-12-24 16:40:51 +00004973 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004974}
4975
Richard Smith0e617ec2016-12-27 07:56:27 +00004976bool Sema::isMoreSpecializedThanPrimary(
4977 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4978 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4979 // FIXME: Cache the injected template arguments rather than recomputing
4980 // them for each partial specialization.
4981 SmallVector<TemplateArgument, 8> PrimaryArgs;
4982 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4983 PrimaryArgs);
4984
4985 TemplateName CanonTemplate =
4986 Context.getCanonicalTemplateName(TemplateName(Primary));
4987 QualType PrimaryT = Context.getTemplateSpecializationType(
4988 CanonTemplate, PrimaryArgs);
4989 QualType PartialT = Context.getTemplateSpecializationType(
4990 CanonTemplate, Spec->getTemplateArgs().asArray());
4991 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4992 return false;
4993 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4994 Info.clearSFINAEDiagnostic();
4995 return false;
4996 }
4997 return true;
4998}
4999
Richard Smith26b86ea2016-12-31 21:41:23 +00005000bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5001 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5002 // C++1z [temp.arg.template]p4: (DR 150)
5003 // A template template-parameter P is at least as specialized as a
5004 // template template-argument A if, given the following rewrite to two
5005 // function templates...
5006
5007 // Rather than synthesize function templates, we merely perform the
5008 // equivalent partial ordering by performing deduction directly on
5009 // the template parameter lists of the template template parameters.
5010 //
5011 // Given an invented class template X with the template parameter list of
5012 // A (including default arguments):
5013 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5014 TemplateParameterList *A = AArg->getTemplateParameters();
5015
5016 // - Each function template has a single function parameter whose type is
5017 // a specialization of X with template arguments corresponding to the
5018 // template parameters from the respective function template
5019 SmallVector<TemplateArgument, 8> AArgs;
5020 Context.getInjectedTemplateArgs(A, AArgs);
5021
5022 // Check P's arguments against A's parameter list. This will fill in default
5023 // template arguments as needed. AArgs are already correct by construction.
5024 // We can't just use CheckTemplateIdType because that will expand alias
5025 // templates.
5026 SmallVector<TemplateArgument, 4> PArgs;
5027 {
5028 SFINAETrap Trap(*this);
5029
5030 Context.getInjectedTemplateArgs(P, PArgs);
5031 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5032 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5033 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5034 // expansions, to form an "as written" argument list.
5035 TemplateArgument Arg = PArgs[I];
5036 if (Arg.getKind() == TemplateArgument::Pack) {
5037 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5038 Arg = *Arg.pack_begin();
5039 }
5040 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5041 Arg, QualType(), P->getParam(I)->getLocation()));
5042 }
5043 PArgs.clear();
5044
5045 // C++1z [temp.arg.template]p3:
5046 // If the rewrite produces an invalid type, then P is not at least as
5047 // specialized as A.
5048 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5049 Trap.hasErrorOccurred())
5050 return false;
5051 }
5052
5053 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5054 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5055
Richard Smith26b86ea2016-12-31 21:41:23 +00005056 // ... the function template corresponding to P is at least as specialized
5057 // as the function template corresponding to A according to the partial
5058 // ordering rules for function templates.
5059 TemplateDeductionInfo Info(Loc, A->getDepth());
5060 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5061}
5062
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005063/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005064/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005065static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005066MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005067 const Expr *E,
5068 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005069 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005070 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005071 // We can deduce from a pack expansion.
5072 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5073 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005074
Richard Smith34349002012-07-09 03:07:20 +00005075 // Skip through any implicit casts we added while type-checking, and any
5076 // substitutions performed by template alias expansion.
5077 while (1) {
5078 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5079 E = ICE->getSubExpr();
5080 else if (const SubstNonTypeTemplateParmExpr *Subst =
5081 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5082 E = Subst->getReplacement();
5083 else
5084 break;
5085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
5087 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005088 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005089 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005090 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005091 return;
5092
Mike Stump11289f42009-09-09 15:08:12 +00005093 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005094 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5095 if (!NTTP)
5096 return;
5097
Douglas Gregor21610382009-10-29 00:04:11 +00005098 if (NTTP->getDepth() == Depth)
5099 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005100
5101 // In C++1z mode, additional arguments may be deduced from the type of a
5102 // non-type argument.
5103 if (Ctx.getLangOpts().CPlusPlus1z)
5104 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005105}
5106
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005107/// \brief Mark the template parameters that are used by the given
5108/// nested name specifier.
5109static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005110MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005111 NestedNameSpecifier *NNS,
5112 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005113 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005114 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005115 if (!NNS)
5116 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005118 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005119 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005120 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005121 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005122}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005124/// \brief Mark the template parameters that are used by the given
5125/// template name.
5126static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005127MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005128 TemplateName Name,
5129 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005130 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005131 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005132 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5133 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005134 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5135 if (TTP->getDepth() == Depth)
5136 Used[TTP->getIndex()] = true;
5137 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005138 return;
5139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005140
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005141 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005142 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005143 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005144 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005145 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005146 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005147}
5148
5149/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005150/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005151static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005152MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005153 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005154 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005155 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005156 if (T.isNull())
5157 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Douglas Gregor91772d12009-06-13 00:26:55 +00005159 // Non-dependent types have nothing deducible
5160 if (!T->isDependentType())
5161 return;
5162
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005163 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005164 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005165 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005166 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005167 cast<PointerType>(T)->getPointeeType(),
5168 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005169 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005170 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005171 break;
5172
5173 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005174 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005175 cast<BlockPointerType>(T)->getPointeeType(),
5176 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005177 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005178 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005179 break;
5180
5181 case Type::LValueReference:
5182 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005183 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005184 cast<ReferenceType>(T)->getPointeeType(),
5185 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005186 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005187 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005188 break;
5189
5190 case Type::MemberPointer: {
5191 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005192 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005193 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005194 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005195 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005196 break;
5197 }
5198
5199 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005200 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005201 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005202 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005203 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005204 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005205
5206 case Type::ConstantArray:
5207 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005208 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005209 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005210 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005211 break;
5212
5213 case Type::Vector:
5214 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005215 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005216 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005217 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005218 break;
5219
Douglas Gregor758a8692009-06-17 21:51:59 +00005220 case Type::DependentSizedExtVector: {
5221 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005222 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005223 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005224 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005225 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005226 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005227 break;
5228 }
5229
Douglas Gregor91772d12009-06-13 00:26:55 +00005230 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005231 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005232 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5233 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005234 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5235 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005236 Depth, Used);
Richard Smithcd198152017-06-07 21:46:22 +00005237 if (auto *E = Proto->getNoexceptExpr())
5238 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005239 break;
5240 }
5241
Douglas Gregor21610382009-10-29 00:04:11 +00005242 case Type::TemplateTypeParm: {
5243 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5244 if (TTP->getDepth() == Depth)
5245 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005246 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005247 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005248
Douglas Gregorfb322d82011-01-14 05:11:40 +00005249 case Type::SubstTemplateTypeParmPack: {
5250 const SubstTemplateTypeParmPackType *Subst
5251 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005252 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005253 QualType(Subst->getReplacedParameter(), 0),
5254 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005255 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005256 OnlyDeduced, Depth, Used);
5257 break;
5258 }
5259
John McCall2408e322010-04-27 00:57:59 +00005260 case Type::InjectedClassName:
5261 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5262 // fall through
5263
Douglas Gregor91772d12009-06-13 00:26:55 +00005264 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005265 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005266 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005267 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005268 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269
Douglas Gregord0ad2942010-12-23 01:24:45 +00005270 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005271 // If the template argument list of P contains a pack expansion that is
5272 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005273 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005275 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005276 break;
5277
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005278 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005279 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005280 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005281 break;
5282 }
5283
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005284 case Type::Complex:
5285 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005286 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005287 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005288 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005289 break;
5290
Eli Friedman0dfb8892011-10-06 23:00:33 +00005291 case Type::Atomic:
5292 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005293 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005294 cast<AtomicType>(T)->getValueType(),
5295 OnlyDeduced, Depth, Used);
5296 break;
5297
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005298 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005299 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005300 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005301 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005302 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005303 break;
5304
John McCallc392f372010-06-11 00:33:02 +00005305 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005306 // C++14 [temp.deduct.type]p5:
5307 // The non-deduced contexts are:
5308 // -- The nested-name-specifier of a type that was specified using a
5309 // qualified-id
5310 //
5311 // C++14 [temp.deduct.type]p6:
5312 // When a type name is specified in a way that includes a non-deduced
5313 // context, all of the types that comprise that type name are also
5314 // non-deduced.
5315 if (OnlyDeduced)
5316 break;
5317
John McCallc392f372010-06-11 00:33:02 +00005318 const DependentTemplateSpecializationType *Spec
5319 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320
Richard Smith50d5b972015-12-30 20:56:05 +00005321 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5322 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005323
John McCallc392f372010-06-11 00:33:02 +00005324 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005325 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005326 Used);
5327 break;
5328 }
5329
John McCallbd8d9bd2010-03-01 23:49:17 +00005330 case Type::TypeOf:
5331 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005332 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005333 cast<TypeOfType>(T)->getUnderlyingType(),
5334 OnlyDeduced, Depth, Used);
5335 break;
5336
5337 case Type::TypeOfExpr:
5338 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005339 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005340 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5341 OnlyDeduced, Depth, Used);
5342 break;
5343
5344 case Type::Decltype:
5345 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005346 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005347 cast<DecltypeType>(T)->getUnderlyingExpr(),
5348 OnlyDeduced, Depth, Used);
5349 break;
5350
Alexis Hunte852b102011-05-24 22:41:36 +00005351 case Type::UnaryTransform:
5352 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005353 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005354 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005355 OnlyDeduced, Depth, Used);
5356 break;
5357
Douglas Gregord2fa7662010-12-20 02:24:11 +00005358 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005359 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005360 cast<PackExpansionType>(T)->getPattern(),
5361 OnlyDeduced, Depth, Used);
5362 break;
5363
Richard Smith30482bc2011-02-20 03:19:35 +00005364 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005365 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005366 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005367 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005368 OnlyDeduced, Depth, Used);
5369
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005370 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005371 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005372 case Type::VariableArray:
5373 case Type::FunctionNoProto:
5374 case Type::Record:
5375 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005376 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005377 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005378 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005379 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005380 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005381#define TYPE(Class, Base)
5382#define ABSTRACT_TYPE(Class, Base)
5383#define DEPENDENT_TYPE(Class, Base)
5384#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5385#include "clang/AST/TypeNodes.def"
5386 break;
5387 }
5388}
5389
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005390/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005391/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005392static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005393MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005394 const TemplateArgument &TemplateArg,
5395 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005396 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005397 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005398 switch (TemplateArg.getKind()) {
5399 case TemplateArgument::Null:
5400 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005401 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005402 break;
Mike Stump11289f42009-09-09 15:08:12 +00005403
Eli Friedmanb826a002012-09-26 02:36:12 +00005404 case TemplateArgument::NullPtr:
5405 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5406 Depth, Used);
5407 break;
5408
Douglas Gregor91772d12009-06-13 00:26:55 +00005409 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005410 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005411 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005412 break;
5413
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005414 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005415 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005416 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005417 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005418 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005419 break;
5420
5421 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005422 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005423 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005424 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Anders Carlssonbc343912009-06-15 17:04:53 +00005426 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005427 for (const auto &P : TemplateArg.pack_elements())
5428 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005429 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005430 }
5431}
5432
James Dennett41725122012-06-22 10:16:05 +00005433/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005434/// template argument list.
5435///
5436/// \param TemplateArgs the template argument list from which template
5437/// parameters will be deduced.
5438///
James Dennett41725122012-06-22 10:16:05 +00005439/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005440/// to indicate when the corresponding template parameter will be
5441/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005442void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005443Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005444 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005445 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005446 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447 // If the template argument list of P contains a pack expansion that is not
5448 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005449 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005451 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005452 return;
5453
Douglas Gregor91772d12009-06-13 00:26:55 +00005454 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005455 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005456 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005457}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005458
5459/// \brief Marks all of the template parameters that will be deduced by a
5460/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005461void Sema::MarkDeducedTemplateParameters(
5462 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5463 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005465 = FunctionTemplate->getTemplateParameters();
5466 Deduced.clear();
5467 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Douglas Gregorce23bae2009-09-18 23:21:38 +00005469 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5470 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005471 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005472 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005473}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005474
Richard Smithf0393bf2017-02-16 04:22:56 +00005475bool hasDeducibleTemplateParameters(Sema &S,
5476 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005477 QualType T) {
5478 if (!T->isDependentType())
5479 return false;
5480
Richard Smithf0393bf2017-02-16 04:22:56 +00005481 TemplateParameterList *TemplateParams
5482 = FunctionTemplate->getTemplateParameters();
5483 llvm::SmallBitVector Deduced(TemplateParams->size());
5484 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5485 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005486
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005487 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005488}