blob: 7750b9c0eaef800cfd7f7ecaa013e31418384064 [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000103 bool PartialOrdering = false,
104 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000105
106static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000107DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000108 ArrayRef<TemplateArgument> Params,
109 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000110 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
112 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000113
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000114/// \brief If the given expression is of a form that permits the deduction
115/// of a non-type template parameter, return the declaration of that
116/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000117static NonTypeTemplateParmDecl *
118getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000119 // If we are within an alias template, the expression may have undergone
120 // any number of parameter substitutions already.
121 while (1) {
122 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
123 E = IC->getSubExpr();
124 else if (SubstNonTypeTemplateParmExpr *Subst =
125 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
126 E = Subst->getReplacement();
127 else
128 break;
129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000131 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000132 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
133 if (NTTP->getDepth() == Info.getDeducedDepth())
134 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000135
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000137}
138
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139/// \brief Determine whether two declaration pointers refer to the same
140/// declaration.
141static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000142 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
143 X = NX->getUnderlyingDecl();
144 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
145 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000146
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000147 return X->getCanonicalDecl() == Y->getCanonicalDecl();
148}
149
150/// \brief Verify that the given, deduced template arguments are compatible.
151///
152/// \returns The deduced template argument, or a NULL template argument if
153/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000155checkDeducedTemplateArguments(ASTContext &Context,
156 const DeducedTemplateArgument &X,
157 const DeducedTemplateArgument &Y) {
158 // We have no deduction for one or both of the arguments; they're compatible.
159 if (X.isNull())
160 return Y;
161 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000162 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000163
Richard Smith593d6a12016-12-23 01:30:39 +0000164 // If we have two non-type template argument values deduced for the same
165 // parameter, they must both match the type of the parameter, and thus must
166 // match each other's type. As we're only keeping one of them, we must check
167 // for that now. The exception is that if either was deduced from an array
168 // bound, the type is permitted to differ.
169 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
170 QualType XType = X.getNonTypeTemplateArgumentType();
171 if (!XType.isNull()) {
172 QualType YType = Y.getNonTypeTemplateArgumentType();
173 if (YType.isNull() || !Context.hasSameType(XType, YType))
174 return DeducedTemplateArgument();
175 }
176 }
177
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000178 switch (X.getKind()) {
179 case TemplateArgument::Null:
180 llvm_unreachable("Non-deduced template arguments handled above");
181
182 case TemplateArgument::Type:
183 // If two template type arguments have the same type, they're compatible.
184 if (Y.getKind() == TemplateArgument::Type &&
185 Context.hasSameType(X.getAsType(), Y.getAsType()))
186 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
Richard Smith5f274382016-09-28 23:55:27 +0000188 // If one of the two arguments was deduced from an array bound, the other
189 // supersedes it.
190 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
191 return X.wasDeducedFromArrayBound() ? Y : X;
192
193 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 case TemplateArgument::Integral:
197 // If we deduced a constant in one case and either a dependent expression or
198 // declaration in another case, keep the integral constant.
199 // If both are integral constants with the same value, keep that value.
200 if (Y.getKind() == TemplateArgument::Expression ||
201 Y.getKind() == TemplateArgument::Declaration ||
202 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000203 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000204 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000205
206 // All other combinations are incompatible.
207 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000208
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000209 case TemplateArgument::Template:
210 if (Y.getKind() == TemplateArgument::Template &&
211 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
212 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000213
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000215 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000216
217 case TemplateArgument::TemplateExpansion:
218 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 Y.getAsTemplateOrTemplatePattern()))
221 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000223 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000225
Richard Smith593d6a12016-12-23 01:30:39 +0000226 case TemplateArgument::Expression: {
227 if (Y.getKind() != TemplateArgument::Expression)
228 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229
Richard Smith593d6a12016-12-23 01:30:39 +0000230 // Compare the expressions for equality
231 llvm::FoldingSetNodeID ID1, ID2;
232 X.getAsExpr()->Profile(ID1, Context, true);
233 Y.getAsExpr()->Profile(ID2, Context, true);
234 if (ID1 == ID2)
235 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Richard Smith593d6a12016-12-23 01:30:39 +0000237 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000242 assert(!X.wasDeducedFromArrayBound());
243
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000244 // If we deduced a declaration and a dependent expression, keep the
245 // declaration.
246 if (Y.getKind() == TemplateArgument::Expression)
247 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000248
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000249 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000250 // integral constant and whichever type did not come from an array
251 // bound.
252 if (Y.getKind() == TemplateArgument::Integral) {
253 if (Y.wasDeducedFromArrayBound())
254 return TemplateArgument(Context, Y.getAsIntegral(),
255 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000258
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000263 return X;
264
265 // All other combinations are incompatible.
266 return DeducedTemplateArgument();
267
268 case TemplateArgument::NullPtr:
269 // If we deduced a null pointer and a dependent expression, keep the
270 // null pointer.
271 if (Y.getKind() == TemplateArgument::Expression)
272 return X;
273
274 // If we deduced a null pointer and an integral constant, keep the
275 // integral constant.
276 if (Y.getKind() == TemplateArgument::Integral)
277 return Y;
278
Richard Smith593d6a12016-12-23 01:30:39 +0000279 // If we deduced two null pointers, they are the same.
280 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 // All other combinations are incompatible.
284 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 case TemplateArgument::Pack:
287 if (Y.getKind() != TemplateArgument::Pack ||
288 X.pack_size() != Y.pack_size())
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
Richard Smith539e8e32017-01-04 01:48:55 +0000291 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000293 XAEnd = X.pack_end(),
294 YA = Y.pack_begin();
295 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000296 TemplateArgument Merged = checkDeducedTemplateArguments(
297 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
298 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
299 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000301 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000303
Richard Smith539e8e32017-01-04 01:48:55 +0000304 return DeducedTemplateArgument(
305 TemplateArgument::CreatePackCopy(Context, NewPack),
306 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308
David Blaikiee4d798f2012-01-20 21:50:17 +0000309 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000310}
311
Mike Stump11289f42009-09-09 15:08:12 +0000312/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000313/// as the given deduced template argument. All non-type template parameter
314/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000315static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000316 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000317 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
318 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000319 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000320 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
321 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000322
Richard Smith5d102892016-12-27 03:59:58 +0000323 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
324 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000325 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000326 Info.Param = NTTP;
327 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000332 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000333 if (!S.getLangOpts().CPlusPlus1z)
334 return Sema::TDK_Success;
335
336 // FIXME: It's not clear how deduction of a parameter of reference
337 // type from an argument (of non-reference type) should be performed.
338 // For now, we just remove reference types from both sides and let
339 // the final check for matching types sort out the mess.
340 return DeduceTemplateArgumentsByTypeMatch(
341 S, TemplateParams, NTTP->getType().getNonReferenceType(),
342 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
343 /*PartialOrdering=*/false,
344 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000345}
346
Mike Stump11289f42009-09-09 15:08:12 +0000347/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000348/// from the given integral constant.
349static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
350 Sema &S, TemplateParameterList *TemplateParams,
351 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
352 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
353 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
354 return DeduceNonTypeTemplateArgument(
355 S, TemplateParams, NTTP,
356 DeducedTemplateArgument(S.Context, Value, ValueType,
357 DeducedFromArrayBound),
358 ValueType, Info, Deduced);
359}
360
361/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000362/// from the given null pointer template argument type.
363static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000364 Sema &S, TemplateParameterList *TemplateParams,
365 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000366 TemplateDeductionInfo &Info,
367 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
368 Expr *Value =
369 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
370 S.Context.NullPtrTy, NTTP->getLocation()),
371 NullPtrType, CK_NullToPointer)
372 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000373 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
374 DeducedTemplateArgument(Value),
375 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000376}
377
378/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000379/// from the given type- or value-dependent expression.
380///
381/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000382static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
383 Sema &S, TemplateParameterList *TemplateParams,
384 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
385 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000386 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
387 DeducedTemplateArgument(Value),
388 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000389}
390
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000391/// \brief Deduce the value of the given non-type template parameter
392/// from the given declaration.
393///
394/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000395static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
396 Sema &S, TemplateParameterList *TemplateParams,
397 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
398 TemplateDeductionInfo &Info,
399 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000401 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000402 return DeduceNonTypeTemplateArgument(
403 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000404}
405
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000406static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000407DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000408 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000409 TemplateName Param,
410 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000411 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000412 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000413 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000414 if (!ParamDecl) {
415 // The parameter type is dependent and is not a template template parameter,
416 // so there is nothing that we can deduce.
417 return Sema::TDK_Success;
418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
Douglas Gregoradee3e32009-11-11 23:06:43 +0000420 if (TemplateTemplateParmDecl *TempParam
421 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000422 // If we're not deducing at this depth, there's nothing to deduce.
423 if (TempParam->getDepth() != Info.getDeducedDepth())
424 return Sema::TDK_Success;
425
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000426 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000428 Deduced[TempParam->getIndex()],
429 NewDeduced);
430 if (Result.isNull()) {
431 Info.Param = TempParam;
432 Info.FirstArg = Deduced[TempParam->getIndex()];
433 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000437 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
Douglas Gregoradee3e32009-11-11 23:06:43 +0000441 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000442 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000443 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444
Douglas Gregoradee3e32009-11-11 23:06:43 +0000445 // Mismatch of non-dependent template parameter to argument.
446 Info.FirstArg = TemplateArgument(Param);
447 Info.SecondArg = TemplateArgument(Arg);
448 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000449}
450
Mike Stump11289f42009-09-09 15:08:12 +0000451/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000452/// type (which is a template-id) with the template argument type.
453///
Chandler Carruthc1263112010-02-07 21:33:28 +0000454/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000455///
456/// \param TemplateParams the template parameters that we are deducing
457///
458/// \param Param the parameter type
459///
460/// \param Arg the argument type
461///
462/// \param Info information about the template argument deduction itself
463///
464/// \param Deduced the deduced template arguments
465///
466/// \returns the result of template argument deduction so far. Note that a
467/// "success" result means that template argument deduction has not yet failed,
468/// but it may still fail, later, for other reasons.
469static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000470DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000471 TemplateParameterList *TemplateParams,
472 const TemplateSpecializationType *Param,
473 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000474 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000475 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000476 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000477
Douglas Gregore81f3e72009-07-07 23:09:34 +0000478 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000479 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 = dyn_cast<TemplateSpecializationType>(Arg)) {
481 // Perform template argument deduction for the template name.
482 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000483 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000484 Param->getTemplateName(),
485 SpecArg->getTemplateName(),
486 Info, Deduced))
487 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregore81f3e72009-07-07 23:09:34 +0000490 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000491 // argument. Ignore any missing/extra arguments, since they could be
492 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000493 return DeduceTemplateArguments(S, TemplateParams,
494 Param->template_arguments(),
495 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000496 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregore81f3e72009-07-07 23:09:34 +0000499 // If the argument type is a class template specialization, we
500 // perform template argument deduction using its template
501 // arguments.
502 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000503 if (!RecordArg) {
504 Info.FirstArg = TemplateArgument(QualType(Param, 0));
505 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
509 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000511 if (!SpecArg) {
512 Info.FirstArg = TemplateArgument(QualType(Param, 0));
513 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregore81f3e72009-07-07 23:09:34 +0000517 // Perform template argument deduction for the template name.
518 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000519 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000520 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000521 Param->getTemplateName(),
522 TemplateName(SpecArg->getSpecializedTemplate()),
523 Info, Deduced))
524 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregor7baabef2010-12-22 18:17:10 +0000526 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000527 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
528 SpecArg->getTemplateArgs().asArray(), Info,
529 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000530}
531
John McCall08569062010-08-28 22:14:41 +0000532/// \brief Determines whether the given type is an opaque type that
533/// might be more qualified when instantiated.
534static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
535 switch (T->getTypeClass()) {
536 case Type::TypeOfExpr:
537 case Type::TypeOf:
538 case Type::DependentName:
539 case Type::Decltype:
540 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000541 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000542 return true;
543
544 case Type::ConstantArray:
545 case Type::IncompleteArray:
546 case Type::VariableArray:
547 case Type::DependentSizedArray:
548 return IsPossiblyOpaquelyQualifiedType(
549 cast<ArrayType>(T)->getElementType());
550
551 default:
552 return false;
553 }
554}
555
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000556/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000558getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Douglas Gregor5499af42011-01-05 23:12:31 +0000562 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
563 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor5499af42011-01-05 23:12:31 +0000565 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
566 return std::make_pair(TTP->getDepth(), TTP->getIndex());
567}
568
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000569/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000571getDepthAndIndex(UnexpandedParameterPack UPP) {
572 if (const TemplateTypeParmType *TTP
573 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
574 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000576 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
577}
578
Douglas Gregor5499af42011-01-05 23:12:31 +0000579/// \brief Helper function to build a TemplateParameter when we don't
580/// know its type statically.
581static TemplateParameter makeTemplateParameter(Decl *D) {
582 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
583 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000584 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000585 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Douglas Gregor5499af42011-01-05 23:12:31 +0000587 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
588}
589
Richard Smith0a80d572014-05-29 01:12:14 +0000590/// A pack that we're currently deducing.
591struct clang::DeducedPack {
592 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // The index of the pack.
595 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
Richard Smith0a80d572014-05-29 01:12:14 +0000597 // The old value of the pack before we started deducing it.
598 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000599
Richard Smith0a80d572014-05-29 01:12:14 +0000600 // A deferred value of this pack from an inner deduction, that couldn't be
601 // deduced because this deduction hadn't happened yet.
602 DeducedTemplateArgument DeferredDeduction;
603
604 // The new value of the pack.
605 SmallVector<DeducedTemplateArgument, 4> New;
606
607 // The outer deduction for this pack, if any.
608 DeducedPack *Outer;
609};
610
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000611namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000612/// A scope in which we're performing pack deduction.
613class PackDeductionScope {
614public:
615 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
616 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
617 TemplateDeductionInfo &Info, TemplateArgument Pattern)
618 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
619 // Compute the set of template parameter indices that correspond to
620 // parameter packs expanded by the pack expansion.
621 {
622 llvm::SmallBitVector SawIndices(TemplateParams->size());
623 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
624 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
625 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
626 unsigned Depth, Index;
627 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000628 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000629 SawIndices[Index] = true;
630
631 // Save the deduced template argument for the parameter pack expanded
632 // by this pack expansion, then clear out the deduction.
633 DeducedPack Pack(Index);
634 Pack.Saved = Deduced[Index];
635 Deduced[Index] = TemplateArgument();
636
637 Packs.push_back(Pack);
638 }
639 }
640 }
641 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
642
643 for (auto &Pack : Packs) {
644 if (Info.PendingDeducedPacks.size() > Pack.Index)
645 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
646 else
647 Info.PendingDeducedPacks.resize(Pack.Index + 1);
648 Info.PendingDeducedPacks[Pack.Index] = &Pack;
649
650 if (S.CurrentInstantiationScope) {
651 // If the template argument pack was explicitly specified, add that to
652 // the set of deduced arguments.
653 const TemplateArgument *ExplicitArgs;
654 unsigned NumExplicitArgs;
655 NamedDecl *PartiallySubstitutedPack =
656 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
657 &ExplicitArgs, &NumExplicitArgs);
658 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000659 getDepthAndIndex(PartiallySubstitutedPack) ==
660 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000661 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
662 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000663 }
664 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000665
Richard Smith0a80d572014-05-29 01:12:14 +0000666 ~PackDeductionScope() {
667 for (auto &Pack : Packs)
668 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Richard Smith0a80d572014-05-29 01:12:14 +0000671 /// Move to deducing the next element in each pack that is being deduced.
672 void nextPackElement() {
673 // Capture the deduced template arguments for each parameter pack expanded
674 // by this pack expansion, add them to the list of arguments we've deduced
675 // for that pack, then clear out the deduced argument.
676 for (auto &Pack : Packs) {
677 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000678 if (!Pack.New.empty() || !DeducedArg.isNull()) {
679 while (Pack.New.size() < PackElements)
680 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith0a80d572014-05-29 01:12:14 +0000681 Pack.New.push_back(DeducedArg);
682 DeducedArg = DeducedTemplateArgument();
683 }
684 }
Richard Smith539e8e32017-01-04 01:48:55 +0000685 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000686 }
687
688 /// \brief Finish template argument deduction for a set of argument packs,
689 /// producing the argument packs and checking for consistency with prior
690 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000691 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000692 // Build argument packs for each of the parameter packs expanded by this
693 // pack expansion.
694 for (auto &Pack : Packs) {
695 // Put back the old value for this pack.
696 Deduced[Pack.Index] = Pack.Saved;
697
698 // Build or find a new value for this pack.
699 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000700 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000701 if (Pack.DeferredDeduction.isNull()) {
702 // We were not able to deduce anything for this parameter pack
703 // (because it only appeared in non-deduced contexts), so just
704 // restore the saved argument pack.
705 continue;
706 }
707
708 NewPack = Pack.DeferredDeduction;
709 Pack.DeferredDeduction = TemplateArgument();
710 } else if (Pack.New.empty()) {
711 // If we deduced an empty argument pack, create it now.
712 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
713 } else {
714 TemplateArgument *ArgumentPack =
715 new (S.Context) TemplateArgument[Pack.New.size()];
716 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
717 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000718 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000719 Pack.New[0].wasDeducedFromArrayBound());
720 }
721
722 // Pick where we're going to put the merged pack.
723 DeducedTemplateArgument *Loc;
724 if (Pack.Outer) {
725 if (Pack.Outer->DeferredDeduction.isNull()) {
726 // Defer checking this pack until we have a complete pack to compare
727 // it against.
728 Pack.Outer->DeferredDeduction = NewPack;
729 continue;
730 }
731 Loc = &Pack.Outer->DeferredDeduction;
732 } else {
733 Loc = &Deduced[Pack.Index];
734 }
735
736 // Check the new pack matches any previous value.
737 DeducedTemplateArgument OldPack = *Loc;
738 DeducedTemplateArgument Result =
739 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
740
741 // If we deferred a deduction of this pack, check that one now too.
742 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
743 OldPack = Result;
744 NewPack = Pack.DeferredDeduction;
745 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
746 }
747
748 if (Result.isNull()) {
749 Info.Param =
750 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
751 Info.FirstArg = OldPack;
752 Info.SecondArg = NewPack;
753 return Sema::TDK_Inconsistent;
754 }
755
756 *Loc = Result;
757 }
758
759 return Sema::TDK_Success;
760 }
761
762private:
763 Sema &S;
764 TemplateParameterList *TemplateParams;
765 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
766 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000767 unsigned PackElements = 0;
Richard Smith0a80d572014-05-29 01:12:14 +0000768
769 SmallVector<DeducedPack, 2> Packs;
770};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000771} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000772
Douglas Gregor5499af42011-01-05 23:12:31 +0000773/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774/// types to the list of argument types, as in the parameter-type-lists of
775/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000776///
777/// \param S The semantic analysis object within which we are deducing
778///
779/// \param TemplateParams The template parameters that we are deducing
780///
781/// \param Params The list of parameter types
782///
783/// \param NumParams The number of types in \c Params
784///
785/// \param Args The list of argument types
786///
787/// \param NumArgs The number of types in \c Args
788///
789/// \param Info information about the template argument deduction itself
790///
791/// \param Deduced the deduced template arguments
792///
793/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
794/// how template argument deduction is performed.
795///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000796/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000798/// (C++0x [temp.deduct.partial]).
799///
Douglas Gregor5499af42011-01-05 23:12:31 +0000800/// \returns the result of template argument deduction so far. Note that a
801/// "success" result means that template argument deduction has not yet failed,
802/// but it may still fail, later, for other reasons.
803static Sema::TemplateDeductionResult
804DeduceTemplateArguments(Sema &S,
805 TemplateParameterList *TemplateParams,
806 const QualType *Params, unsigned NumParams,
807 const QualType *Args, unsigned NumArgs,
808 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000809 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000810 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000811 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000812 // Fast-path check to see if we have too many/too few arguments.
813 if (NumParams != NumArgs &&
814 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
815 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000816 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor5499af42011-01-05 23:12:31 +0000818 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // Similarly, if P has a form that contains (T), then each parameter type
820 // Pi of the respective parameter-type- list of P is compared with the
821 // corresponding parameter type Ai of the corresponding parameter-type-list
822 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000823 unsigned ArgIdx = 0, ParamIdx = 0;
824 for (; ParamIdx != NumParams; ++ParamIdx) {
825 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000827 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
828 if (!Expansion) {
829 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 // Make sure we have an argument.
832 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000833 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000835 if (isa<PackExpansionType>(Args[ArgIdx])) {
836 // C++0x [temp.deduct.type]p22:
837 // If the original function parameter associated with A is a function
838 // parameter pack and the function parameter associated with P is not
839 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000840 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000844 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
845 Params[ParamIdx], Args[ArgIdx],
846 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000847 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Douglas Gregor5499af42011-01-05 23:12:31 +0000850 ++ArgIdx;
851 continue;
852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000854 // C++0x [temp.deduct.type]p5:
855 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000857 // parameter-declaration-clause.
858 if (ParamIdx + 1 < NumParams)
859 return Sema::TDK_Success;
860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000863 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 // comparison deduces template arguments for subsequent positions in the
866 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000869 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870
Douglas Gregor5499af42011-01-05 23:12:31 +0000871 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000872 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000873 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000874 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
875 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000876 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Richard Smith0a80d572014-05-29 01:12:14 +0000879 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 // Build argument packs for each of the parameter packs expanded by this
883 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000884 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Douglas Gregor5499af42011-01-05 23:12:31 +0000888 // Make sure we don't have any extra arguments.
889 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000890 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
Douglas Gregor5499af42011-01-05 23:12:31 +0000892 return Sema::TDK_Success;
893}
894
Douglas Gregor1d684c22011-04-28 00:56:09 +0000895/// \brief Determine whether the parameter has qualifiers that are either
896/// inconsistent with or a superset of the argument's qualifiers.
897static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
898 QualType ArgType) {
899 Qualifiers ParamQs = ParamType.getQualifiers();
900 Qualifiers ArgQs = ArgType.getQualifiers();
901
902 if (ParamQs == ArgQs)
903 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000904
Douglas Gregor1d684c22011-04-28 00:56:09 +0000905 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000906 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000907 ParamQs.hasObjCGCAttr())
908 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000909
Douglas Gregor1d684c22011-04-28 00:56:09 +0000910 // Mismatched (but not missing) address spaces.
911 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
912 ParamQs.hasAddressSpace())
913 return true;
914
John McCall31168b02011-06-15 23:02:42 +0000915 // Mismatched (but not missing) Objective-C lifetime qualifiers.
916 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
917 ParamQs.hasObjCLifetime())
918 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000919
Douglas Gregor1d684c22011-04-28 00:56:09 +0000920 // CVR qualifier superset.
921 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
922 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
923 == ParamQs.getCVRQualifiers());
924}
925
Douglas Gregor19a41f12013-04-17 08:45:07 +0000926/// \brief Compare types for equality with respect to possibly compatible
927/// function types (noreturn adjustment, implicit calling conventions). If any
928/// of parameter and argument is not a function, just perform type comparison.
929///
930/// \param Param the template parameter type.
931///
932/// \param Arg the argument type.
933bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
934 CanQualType Arg) {
935 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
936 *ArgFunction = Arg->getAs<FunctionType>();
937
938 // Just compare if not functions.
939 if (!ParamFunction || !ArgFunction)
940 return Param == Arg;
941
Richard Smith3c4f8d22016-10-16 17:54:23 +0000942 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000943 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000944 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000945 return Arg == Context.getCanonicalType(AdjustedParam);
946
947 // FIXME: Compatible calling conventions.
948
949 return Param == Arg;
950}
951
Douglas Gregorcceb9752009-06-26 18:27:22 +0000952/// \brief Deduce the template arguments by comparing the parameter type and
953/// the argument type (C++ [temp.deduct.type]).
954///
Chandler Carruthc1263112010-02-07 21:33:28 +0000955/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000956///
957/// \param TemplateParams the template parameters that we are deducing
958///
959/// \param ParamIn the parameter type
960///
961/// \param ArgIn the argument type
962///
963/// \param Info information about the template argument deduction itself
964///
965/// \param Deduced the deduced template arguments
966///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000967/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000968/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000969///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000970/// \param PartialOrdering Whether we're performing template argument deduction
971/// in the context of partial ordering (C++0x [temp.deduct.partial]).
972///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000973/// \returns the result of template argument deduction so far. Note that a
974/// "success" result means that template argument deduction has not yet failed,
975/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000976static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000977DeduceTemplateArgumentsByTypeMatch(Sema &S,
978 TemplateParameterList *TemplateParams,
979 QualType ParamIn, QualType ArgIn,
980 TemplateDeductionInfo &Info,
981 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
982 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000983 bool PartialOrdering,
984 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000985 // We only want to look at the canonical types, since typedefs and
986 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000987 QualType Param = S.Context.getCanonicalType(ParamIn);
988 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000989
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000990 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000992 if (const PackExpansionType *ArgExpansion
993 = dyn_cast<PackExpansionType>(Arg))
994 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
Douglas Gregorb837ea42011-01-11 17:34:58 +0000996 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000997 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000998 // Before the partial ordering is done, certain transformations are
999 // performed on the types used for partial ordering:
1000 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001001 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1002 if (ParamRef)
1003 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001004
Douglas Gregorb837ea42011-01-11 17:34:58 +00001005 // - If A is a reference type, A is replaced by the type referred to.
1006 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1007 if (ArgRef)
1008 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Richard Smithed563c22015-02-20 04:45:22 +00001010 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1011 // C++11 [temp.deduct.partial]p9:
1012 // If, for a given type, deduction succeeds in both directions (i.e.,
1013 // the types are identical after the transformations above) and both
1014 // P and A were reference types [...]:
1015 // - if [one type] was an lvalue reference and [the other type] was
1016 // not, [the other type] is not considered to be at least as
1017 // specialized as [the first type]
1018 // - if [one type] is more cv-qualified than [the other type],
1019 // [the other type] is not considered to be at least as specialized
1020 // as [the first type]
1021 // Objective-C ARC adds:
1022 // - [one type] has non-trivial lifetime, [the other type] has
1023 // __unsafe_unretained lifetime, and the types are otherwise
1024 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001025 //
Richard Smithed563c22015-02-20 04:45:22 +00001026 // A is "considered to be at least as specialized" as P iff deduction
1027 // succeeds, so we model this as a deduction failure. Note that
1028 // [the first type] is P and [the other type] is A here; the standard
1029 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001030 Qualifiers ParamQuals = Param.getQualifiers();
1031 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001032 if ((ParamRef->isLValueReferenceType() &&
1033 !ArgRef->isLValueReferenceType()) ||
1034 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1035 (ParamQuals.hasNonTrivialObjCLifetime() &&
1036 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1037 ParamQuals.withoutObjCLifetime() ==
1038 ArgQuals.withoutObjCLifetime())) {
1039 Info.FirstArg = TemplateArgument(ParamIn);
1040 Info.SecondArg = TemplateArgument(ArgIn);
1041 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001042 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Richard Smithed563c22015-02-20 04:45:22 +00001045 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001048 // version of P.
1049 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001051 // version of A.
1052 Arg = Arg.getUnqualifiedType();
1053 } else {
1054 // C++0x [temp.deduct.call]p4 bullet 1:
1055 // - If the original P is a reference type, the deduced A (i.e., the type
1056 // referred to by the reference) can be more cv-qualified than the
1057 // transformed A.
1058 if (TDF & TDF_ParamWithReferenceType) {
1059 Qualifiers Quals;
1060 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1061 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001062 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001063 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
Douglas Gregor85f240c2011-01-25 17:19:08 +00001066 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1067 // C++0x [temp.deduct.type]p10:
1068 // If P and A are function types that originated from deduction when
1069 // taking the address of a function template (14.8.2.2) or when deducing
1070 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071 // Ai are parameters of the top-level parameter-type-list of P and A,
1072 // respectively, Pi is adjusted if it is an rvalue reference to a
1073 // cv-unqualified template parameter and Ai is an lvalue reference, in
1074 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001075 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1076 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001077 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001078 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Douglas Gregor85f240c2011-01-25 17:19:08 +00001080 if (const RValueReferenceType *ParamRef
1081 = Param->getAs<RValueReferenceType>()) {
1082 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1083 !ParamRef->getPointeeType().getQualifiers())
1084 if (Arg->isLValueReferenceType())
1085 Param = ParamRef->getPointeeType();
1086 }
1087 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001090 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001091 // A template type argument T, a template template argument TT or a
1092 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001093 // the following forms:
1094 //
1095 // T
1096 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001098 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001099 // Just skip any attempts to deduce from a placeholder type or a parameter
1100 // at a different depth.
1101 if (Arg->isPlaceholderType() ||
1102 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001103 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001104
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001105 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001106 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor60454822009-07-22 20:02:25 +00001108 // If the argument type is an array type, move the qualifiers up to the
1109 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001110 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001111 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001112 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001113 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001114 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001115 RecanonicalizeArg = true;
1116 }
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001119 // The argument type can not be less qualified than the parameter
1120 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001121 if (!(TDF & TDF_IgnoreQualifiers) &&
1122 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001123 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001124 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001125 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001126 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001127 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001128
Richard Smith87d263e2016-12-25 08:05:23 +00001129 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1130 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001131 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001132 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001133
Douglas Gregor1d684c22011-04-28 00:56:09 +00001134 // Remove any qualifiers on the parameter from the deduced type.
1135 // We checked the qualifiers for consistency above.
1136 Qualifiers DeducedQs = DeducedType.getQualifiers();
1137 Qualifiers ParamQs = Param.getQualifiers();
1138 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1139 if (ParamQs.hasObjCGCAttr())
1140 DeducedQs.removeObjCGCAttr();
1141 if (ParamQs.hasAddressSpace())
1142 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001143 if (ParamQs.hasObjCLifetime())
1144 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001145
Douglas Gregore46db902011-06-17 22:11:49 +00001146 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001147 // If template deduction would produce a lifetime qualifier on a type
1148 // that is not a lifetime type, template argument deduction fails.
1149 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1150 !DeducedType->isDependentType()) {
1151 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1152 Info.FirstArg = TemplateArgument(Param);
1153 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001154 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001155 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001156
Douglas Gregora4f2b432011-07-26 14:53:44 +00001157 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001158 // If template deduction would produce an argument type with lifetime type
1159 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001160 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001161 DeducedType->isObjCLifetimeType() &&
1162 !DeducedQs.hasObjCLifetime())
1163 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001164
Douglas Gregor1d684c22011-04-28 00:56:09 +00001165 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1166 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001167
Douglas Gregord6605db2009-07-22 21:30:48 +00001168 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001169 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001170
Richard Smith5f274382016-09-28 23:55:27 +00001171 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001173 Deduced[Index],
1174 NewDeduced);
1175 if (Result.isNull()) {
1176 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1177 Info.FirstArg = Deduced[Index];
1178 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001182 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001184 }
1185
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001186 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001187 Info.FirstArg = TemplateArgument(ParamIn);
1188 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001189
Douglas Gregorfb322d82011-01-14 05:11:40 +00001190 // If the parameter is an already-substituted template parameter
1191 // pack, do nothing: we don't know which of its arguments to look
1192 // at, so we have to wait until all of the parameter packs in this
1193 // expansion have arguments.
1194 if (isa<SubstTemplateTypeParmPackType>(Param))
1195 return Sema::TDK_Success;
1196
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001197 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001198 CanQualType CanParam = S.Context.getCanonicalType(Param);
1199 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001200 if (!(TDF & TDF_IgnoreQualifiers)) {
1201 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001202 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001204 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001205 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001206 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001207 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001208
Douglas Gregor194ea692012-03-11 03:29:50 +00001209 // If the parameter type is not dependent, there is nothing to deduce.
1210 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001211 if (!(TDF & TDF_SkipNonDependent)) {
1212 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1213 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1214 Param != Arg;
1215 if (NonDeduced) {
1216 return Sema::TDK_NonDeducedMismatch;
1217 }
1218 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001219 return Sema::TDK_Success;
1220 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001221 } else if (!Param->isDependentType()) {
1222 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1223 ArgUnqualType = CanArg.getUnqualifiedType();
1224 bool Success = (TDF & TDF_InOverloadResolution)?
1225 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1226 ArgUnqualType) :
1227 ParamUnqualType == ArgUnqualType;
1228 if (Success)
1229 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001230 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001231
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001232 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001233 // Non-canonical types cannot appear here.
1234#define NON_CANONICAL_TYPE(Class, Base) \
1235 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1236#define TYPE(Class, Base)
1237#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001238
Douglas Gregor39c02722011-06-15 16:02:29 +00001239 case Type::TemplateTypeParm:
1240 case Type::SubstTemplateTypeParmPack:
1241 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001242
1243 // These types cannot be dependent, so simply check whether the types are
1244 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001245 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001246 case Type::VariableArray:
1247 case Type::Vector:
1248 case Type::FunctionNoProto:
1249 case Type::Record:
1250 case Type::Enum:
1251 case Type::ObjCObject:
1252 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001253 case Type::ObjCObjectPointer: {
1254 if (TDF & TDF_SkipNonDependent)
1255 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001256
Douglas Gregor194ea692012-03-11 03:29:50 +00001257 if (TDF & TDF_IgnoreQualifiers) {
1258 Param = Param.getUnqualifiedType();
1259 Arg = Arg.getUnqualifiedType();
1260 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001261
Douglas Gregor194ea692012-03-11 03:29:50 +00001262 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1263 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001264
1265 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001266 case Type::Complex:
1267 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001268 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1269 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001270 ComplexArg->getElementType(),
1271 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001272
1273 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001274
1275 // _Atomic T [extension]
1276 case Type::Atomic:
1277 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001278 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001279 cast<AtomicType>(Param)->getValueType(),
1280 AtomicArg->getValueType(),
1281 Info, Deduced, TDF);
1282
1283 return Sema::TDK_NonDeducedMismatch;
1284
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001285 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001286 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001287 QualType PointeeType;
1288 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1289 PointeeType = PointerArg->getPointeeType();
1290 } else if (const ObjCObjectPointerType *PointerArg
1291 = Arg->getAs<ObjCObjectPointerType>()) {
1292 PointeeType = PointerArg->getPointeeType();
1293 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001294 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregorfc516c92009-06-26 23:27:24 +00001297 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001298 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1299 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001300 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001301 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001304 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001305 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001306 const LValueReferenceType *ReferenceArg =
1307 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001308 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001309 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001310
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001311 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001313 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001314 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001315
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001316 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001317 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001318 const RValueReferenceType *ReferenceArg =
1319 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001320 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001321 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001323 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1324 cast<RValueReferenceType>(Param)->getPointeeType(),
1325 ReferenceArg->getPointeeType(),
1326 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001329 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001330 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001331 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001332 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001333 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001334 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001335
John McCallf7332682010-08-19 00:20:19 +00001336 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1338 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1339 IncompleteArrayArg->getElementType(),
1340 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001341 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342
1343 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001345 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001346 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001347 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001348 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001349
1350 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001351 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001352 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001353 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001354
John McCallf7332682010-08-19 00:20:19 +00001355 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001356 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1357 ConstantArrayParm->getElementType(),
1358 ConstantArrayArg->getElementType(),
1359 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001360 }
1361
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001362 // type [i]
1363 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001364 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001365 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001366 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCallf7332682010-08-19 00:20:19 +00001368 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1369
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001370 // Check the element type of the arrays
1371 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001372 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001373 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001374 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1375 DependentArrayParm->getElementType(),
1376 ArrayArg->getElementType(),
1377 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001378 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001379
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001380 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001381 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001382 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001383 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001384 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001385
1386 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001388 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1389 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001390 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001391 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1392 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001393 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001394 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001395 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001397 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001398 if (const DependentSizedArrayType *DependentArrayArg
1399 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001400 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001401 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001402 DependentArrayArg->getSizeExpr(),
1403 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001406 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
1409 // type(*)(T)
1410 // T(*)()
1411 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001412 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001413 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001414 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001415 dyn_cast<FunctionProtoType>(Arg);
1416 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001417 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001418
1419 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001420 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001421
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001423 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001425 != FunctionProtoArg->getRefQualifier() ||
1426 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001427 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001428
Anders Carlsson2128ec72009-06-08 15:19:08 +00001429 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001430 if (Sema::TemplateDeductionResult Result =
1431 DeduceTemplateArgumentsByTypeMatch(
1432 S, TemplateParams, FunctionProtoParam->getReturnType(),
1433 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001434 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001435
Alp Toker9cacbab2014-01-20 20:26:09 +00001436 return DeduceTemplateArguments(
1437 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1438 FunctionProtoParam->getNumParams(),
1439 FunctionProtoArg->param_type_begin(),
1440 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
John McCalle78aac42010-03-10 03:28:59 +00001443 case Type::InjectedClassName: {
1444 // Treat a template's injected-class-name as if the template
1445 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001446 Param = cast<InjectedClassNameType>(Param)
1447 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001448 assert(isa<TemplateSpecializationType>(Param) &&
1449 "injected class name is not a template specialization type");
1450 // fall through
1451 }
1452
Douglas Gregor705c9002009-06-26 20:57:09 +00001453 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001454 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001455 // TT<T>
1456 // TT<i>
1457 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001458 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001459 const TemplateSpecializationType *SpecParam =
1460 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Richard Smith9b296e32016-04-25 19:09:05 +00001462 // When Arg cannot be a derived class, we can just try to deduce template
1463 // arguments from the template-id.
1464 const RecordType *RecordT = Arg->getAs<RecordType>();
1465 if (!(TDF & TDF_DerivedClass) || !RecordT)
1466 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1467 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Richard Smith9b296e32016-04-25 19:09:05 +00001469 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1470 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001471
Richard Smith9b296e32016-04-25 19:09:05 +00001472 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1473 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Richard Smith9b296e32016-04-25 19:09:05 +00001475 if (Result == Sema::TDK_Success)
1476 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001477
Richard Smith9b296e32016-04-25 19:09:05 +00001478 // We cannot inspect base classes as part of deduction when the type
1479 // is incomplete, so either instantiate any templates necessary to
1480 // complete the type, or skip over it if it cannot be completed.
1481 if (!S.isCompleteType(Info.getLocation(), Arg))
1482 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001483
Richard Smith9b296e32016-04-25 19:09:05 +00001484 // C++14 [temp.deduct.call] p4b3:
1485 // If P is a class and P has the form simple-template-id, then the
1486 // transformed A can be a derived class of the deduced A. Likewise if
1487 // P is a pointer to a class of the form simple-template-id, the
1488 // transformed A can be a pointer to a derived class pointed to by the
1489 // deduced A.
1490 //
1491 // These alternatives are considered only if type deduction would
1492 // otherwise fail. If they yield more than one possible deduced A, the
1493 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001494
Faisal Vali683b0742016-05-19 02:28:21 +00001495 // Reset the incorrectly deduced argument from above.
1496 Deduced = DeducedOrig;
1497
1498 // Use data recursion to crawl through the list of base classes.
1499 // Visited contains the set of nodes we have already visited, while
1500 // ToVisit is our stack of records that we still need to visit.
1501 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1502 SmallVector<const RecordType *, 8> ToVisit;
1503 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001504 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001505 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001506 while (!ToVisit.empty()) {
1507 // Retrieve the next class in the inheritance hierarchy.
1508 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001509
Faisal Vali683b0742016-05-19 02:28:21 +00001510 // If we have already seen this type, skip it.
1511 if (!Visited.insert(NextT).second)
1512 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001513
Faisal Vali683b0742016-05-19 02:28:21 +00001514 // If this is a base class, try to perform template argument
1515 // deduction from it.
1516 if (NextT != RecordT) {
1517 TemplateDeductionInfo BaseInfo(Info.getLocation());
1518 Sema::TemplateDeductionResult BaseResult =
1519 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1520 QualType(NextT, 0), BaseInfo, Deduced);
1521
1522 // If template argument deduction for this base was successful,
1523 // note that we had some success. Otherwise, ignore any deductions
1524 // from this base class.
1525 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001526 // If we've already seen some success, then deduction fails due to
1527 // an ambiguity (temp.deduct.call p5).
1528 if (Successful)
1529 return Sema::TDK_MiscellaneousDeductionFailure;
1530
Faisal Vali683b0742016-05-19 02:28:21 +00001531 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001532 std::swap(SuccessfulDeduced, Deduced);
1533
Faisal Vali683b0742016-05-19 02:28:21 +00001534 Info.Param = BaseInfo.Param;
1535 Info.FirstArg = BaseInfo.FirstArg;
1536 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001537 }
1538
1539 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Faisal Vali683b0742016-05-19 02:28:21 +00001542 // Visit base classes
1543 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1544 for (const auto &Base : Next->bases()) {
1545 assert(Base.getType()->isRecordType() &&
1546 "Base class that isn't a record?");
1547 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1548 }
1549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 if (Successful) {
1552 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001553 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001554 }
Richard Smith9b296e32016-04-25 19:09:05 +00001555
Douglas Gregore81f3e72009-07-07 23:09:34 +00001556 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001557 }
1558
Douglas Gregor637d9982009-06-10 23:47:09 +00001559 // T type::*
1560 // T T::*
1561 // T (type::*)()
1562 // type (T::*)()
1563 // type (type::*)(T)
1564 // type (T::*)(T)
1565 // T (type::*)(T)
1566 // T (T::*)()
1567 // T (T::*)(T)
1568 case Type::MemberPointer: {
1569 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1570 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1571 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001572 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001573
David Majnemera381cda2015-11-30 20:34:28 +00001574 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1575 if (ParamPointeeType->isFunctionType())
1576 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1577 /*IsCtorOrDtor=*/false, Info.getLocation());
1578 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1579 if (ArgPointeeType->isFunctionType())
1580 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1581 /*IsCtorOrDtor=*/false, Info.getLocation());
1582
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001583 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001584 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001585 ParamPointeeType,
1586 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001587 Info, Deduced,
1588 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001589 return Result;
1590
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001591 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1592 QualType(MemPtrParam->getClass(), 0),
1593 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001594 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001595 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001596 }
1597
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001598 // (clang extension)
1599 //
Mike Stump11289f42009-09-09 15:08:12 +00001600 // type(^)(T)
1601 // T(^)()
1602 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001603 case Type::BlockPointer: {
1604 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1605 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Anders Carlssona767eee2009-06-12 16:23:10 +00001607 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001608 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001609
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001610 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1611 BlockPtrParam->getPointeeType(),
1612 BlockPtrArg->getPointeeType(),
1613 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001614 }
1615
Douglas Gregor39c02722011-06-15 16:02:29 +00001616 // (clang extension)
1617 //
1618 // T __attribute__(((ext_vector_type(<integral constant>))))
1619 case Type::ExtVector: {
1620 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1621 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1622 // Make sure that the vectors have the same number of elements.
1623 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1624 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001625
Douglas Gregor39c02722011-06-15 16:02:29 +00001626 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001627 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628 VectorParam->getElementType(),
1629 VectorArg->getElementType(),
1630 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001631 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001632
1633 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001634 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1635 // We can't check the number of elements, since the argument has a
1636 // dependent number of elements. This can only occur during partial
1637 // ordering.
1638
1639 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001640 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1641 VectorParam->getElementType(),
1642 VectorArg->getElementType(),
1643 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001644 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001645
Douglas Gregor39c02722011-06-15 16:02:29 +00001646 return Sema::TDK_NonDeducedMismatch;
1647 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001648
Douglas Gregor39c02722011-06-15 16:02:29 +00001649 // (clang extension)
1650 //
1651 // T __attribute__(((ext_vector_type(N))))
1652 case Type::DependentSizedExtVector: {
1653 const DependentSizedExtVectorType *VectorParam
1654 = cast<DependentSizedExtVectorType>(Param);
1655
1656 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1657 // Perform deduction on the element types.
1658 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001659 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1660 VectorParam->getElementType(),
1661 VectorArg->getElementType(),
1662 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001663 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001664
Douglas Gregor39c02722011-06-15 16:02:29 +00001665 // Perform deduction on the vector size, if we can.
1666 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001667 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001668 if (!NTTP)
1669 return Sema::TDK_Success;
1670
1671 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1672 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001673 // Note that we use the "array bound" rules here; just like in that
1674 // case, we don't have any particular type for the vector size, but
1675 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001676 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001677 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001678 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001679 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001680
1681 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001682 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1683 // Perform deduction on the element types.
1684 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001685 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1686 VectorParam->getElementType(),
1687 VectorArg->getElementType(),
1688 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001689 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001690
Douglas Gregor39c02722011-06-15 16:02:29 +00001691 // Perform deduction on the vector size, if we can.
1692 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001693 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001694 if (!NTTP)
1695 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001696
Richard Smith5f274382016-09-28 23:55:27 +00001697 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1698 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001699 Info, Deduced);
1700 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001701
Douglas Gregor39c02722011-06-15 16:02:29 +00001702 return Sema::TDK_NonDeducedMismatch;
1703 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001704
Douglas Gregor637d9982009-06-10 23:47:09 +00001705 case Type::TypeOfExpr:
1706 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001707 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001708 case Type::UnresolvedUsing:
1709 case Type::Decltype:
1710 case Type::UnaryTransform:
1711 case Type::Auto:
1712 case Type::DependentTemplateSpecialization:
1713 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001714 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001715 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001716 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001717 }
1718
David Blaikiee4d798f2012-01-20 21:50:17 +00001719 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001720}
1721
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001722static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001723DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001724 TemplateParameterList *TemplateParams,
1725 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001726 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001727 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001728 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001729 // If the template argument is a pack expansion, perform template argument
1730 // deduction against the pattern of that expansion. This only occurs during
1731 // partial ordering.
1732 if (Arg.isPackExpansion())
1733 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001735 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001736 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001737 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001738
1739 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001740 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001741 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1742 Param.getAsType(),
1743 Arg.getAsType(),
1744 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745 Info.FirstArg = Param;
1746 Info.SecondArg = Arg;
1747 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001748
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001749 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001750 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001752 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001753 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001754 Info.FirstArg = Param;
1755 Info.SecondArg = Arg;
1756 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001757
1758 case TemplateArgument::TemplateExpansion:
1759 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001762 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001763 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001764 return Sema::TDK_Success;
1765
1766 Info.FirstArg = Param;
1767 Info.SecondArg = Arg;
1768 return Sema::TDK_NonDeducedMismatch;
1769
1770 case TemplateArgument::NullPtr:
1771 if (Arg.getKind() == TemplateArgument::NullPtr &&
1772 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001773 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001775 Info.FirstArg = Param;
1776 Info.SecondArg = Arg;
1777 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001779 case TemplateArgument::Integral:
1780 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001781 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001782 return Sema::TDK_Success;
1783
1784 Info.FirstArg = Param;
1785 Info.SecondArg = Arg;
1786 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001788
1789 if (Arg.getKind() == TemplateArgument::Expression) {
1790 Info.FirstArg = Param;
1791 Info.SecondArg = Arg;
1792 return Sema::TDK_NonDeducedMismatch;
1793 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001794
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001795 Info.FirstArg = Param;
1796 Info.SecondArg = Arg;
1797 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001798
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001799 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001800 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001801 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001802 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001803 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001804 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001805 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001806 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001807 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001808 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001809 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1810 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001811 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001812 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001813 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1814 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001815 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001816 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1817 Arg.getAsDecl(),
1818 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001819 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001821 Info.FirstArg = Param;
1822 Info.SecondArg = Arg;
1823 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001826 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001827 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001828 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001829 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001830 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
David Blaikiee4d798f2012-01-20 21:50:17 +00001833 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001834}
1835
Douglas Gregor7baabef2010-12-22 18:17:10 +00001836/// \brief Determine whether there is a template argument to be used for
1837/// deduction.
1838///
1839/// This routine "expands" argument packs in-place, overriding its input
1840/// parameters so that \c Args[ArgIdx] will be the available template argument.
1841///
1842/// \returns true if there is another template argument (which will be at
1843/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001844static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1845 unsigned &ArgIdx) {
1846 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001847 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001848
Douglas Gregor7baabef2010-12-22 18:17:10 +00001849 const TemplateArgument &Arg = Args[ArgIdx];
1850 if (Arg.getKind() != TemplateArgument::Pack)
1851 return true;
1852
Richard Smith0bda5b52016-12-23 23:46:56 +00001853 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1854 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001855 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001856 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001857}
1858
Douglas Gregord0ad2942010-12-23 01:24:45 +00001859/// \brief Determine whether the given set of template arguments has a pack
1860/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001861static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1862 bool FoundPackExpansion = false;
1863 for (const auto &A : Args) {
1864 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001865 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001866
1867 if (A.getKind() == TemplateArgument::Pack)
1868 return hasPackExpansionBeforeEnd(A.pack_elements());
1869
1870 if (A.isPackExpansion())
1871 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Douglas Gregord0ad2942010-12-23 01:24:45 +00001874 return false;
1875}
1876
Douglas Gregor7baabef2010-12-22 18:17:10 +00001877static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001878DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001879 ArrayRef<TemplateArgument> Params,
1880 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001881 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001882 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1883 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001884 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 // If the template argument list of P contains a pack expansion that is not
1886 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001888 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001889 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892 // If P has a form that contains <T> or <i>, then each argument Pi of the
1893 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001896 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001897 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001898 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Douglas Gregor7baabef2010-12-22 18:17:10 +00001900 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001901 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001902 return NumberOfArgumentsMustMatch
1903 ? Sema::TDK_MiscellaneousDeductionFailure
1904 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
Richard Smith26b86ea2016-12-31 21:41:23 +00001906 // C++1z [temp.deduct.type]p9:
1907 // During partial ordering, if Ai was originally a pack expansion [and]
1908 // Pi is not a pack expansion, template argument deduction fails.
1909 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001910 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001912 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001913 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001914 = DeduceTemplateArguments(S, TemplateParams,
1915 Params[ParamIdx], Args[ArgIdx],
1916 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917 return Result;
1918
Douglas Gregor7baabef2010-12-22 18:17:10 +00001919 // Move to the next argument.
1920 ++ArgIdx;
1921 continue;
1922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001924 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001926 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927 // If Pi is a pack expansion, then the pattern of Pi is compared with
1928 // each remaining argument in the template argument list of A. Each
1929 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001930 // template parameter packs expanded by Pi.
1931 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // FIXME: If there are no remaining arguments, we can bail out early
1934 // and set any deduced parameter packs to an empty argument pack.
1935 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936
Richard Smith0a80d572014-05-29 01:12:14 +00001937 // Prepare to deduce the packs within the pattern.
1938 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001939
1940 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001942 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001943 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001944 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001946 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1947 Info, Deduced))
1948 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Richard Smith0a80d572014-05-29 01:12:14 +00001950 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001953 // Build argument packs for each of the parameter packs expanded by this
1954 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001955 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor7baabef2010-12-22 18:17:10 +00001959 return Sema::TDK_Success;
1960}
1961
Mike Stump11289f42009-09-09 15:08:12 +00001962static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001963DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001964 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001965 const TemplateArgumentList &ParamList,
1966 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001967 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001968 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001969 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00001970 ArgList.asArray(), Info, Deduced,
1971 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001972}
1973
Douglas Gregor705c9002009-06-26 20:57:09 +00001974/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001975static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00001976 TemplateArgument X,
1977 const TemplateArgument &Y,
1978 bool PackExpansionMatchesPack = false) {
1979 // If we're checking deduced arguments (X) against original arguments (Y),
1980 // we will have flattened packs to non-expansions in X.
1981 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1982 X = X.getPackExpansionPattern();
1983
Douglas Gregor705c9002009-06-26 20:57:09 +00001984 if (X.getKind() != Y.getKind())
1985 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001986
Douglas Gregor705c9002009-06-26 20:57:09 +00001987 switch (X.getKind()) {
1988 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001989 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor705c9002009-06-26 20:57:09 +00001991 case TemplateArgument::Type:
1992 return Context.getCanonicalType(X.getAsType()) ==
1993 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001994
Douglas Gregor705c9002009-06-26 20:57:09 +00001995 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001996 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001997
1998 case TemplateArgument::NullPtr:
1999 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002001 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002002 case TemplateArgument::TemplateExpansion:
2003 return Context.getCanonicalTemplateName(
2004 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2005 Context.getCanonicalTemplateName(
2006 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Douglas Gregor705c9002009-06-26 20:57:09 +00002008 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002009 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002010
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002011 case TemplateArgument::Expression: {
2012 llvm::FoldingSetNodeID XID, YID;
2013 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002015 return XID == YID;
2016 }
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor705c9002009-06-26 20:57:09 +00002018 case TemplateArgument::Pack:
2019 if (X.pack_size() != Y.pack_size())
2020 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002021
2022 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2023 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002024 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002025 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002026 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002027 return false;
2028
2029 return true;
2030 }
2031
David Blaikiee4d798f2012-01-20 21:50:17 +00002032 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002033}
2034
Douglas Gregorca4686d2011-01-04 23:35:54 +00002035/// \brief Allocate a TemplateArgumentLoc where all locations have
2036/// been initialized to the given location.
2037///
James Dennett634962f2012-06-14 21:40:34 +00002038/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002039/// location information for.
2040///
2041/// \param NTTPType For a declaration template argument, the type of
2042/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002043/// argument. Can be null if no type sugar is available to add to the
2044/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002045///
2046/// \param Loc The source location to use for the resulting template
2047/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002048TemplateArgumentLoc
2049Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2050 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002051 switch (Arg.getKind()) {
2052 case TemplateArgument::Null:
2053 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Douglas Gregorca4686d2011-01-04 23:35:54 +00002055 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002056 return TemplateArgumentLoc(
2057 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002058
Douglas Gregorca4686d2011-01-04 23:35:54 +00002059 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002060 if (NTTPType.isNull())
2061 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002062 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2063 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002064 return TemplateArgumentLoc(TemplateArgument(E), E);
2065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066
Eli Friedmanb826a002012-09-26 02:36:12 +00002067 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002068 if (NTTPType.isNull())
2069 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002070 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2071 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002072 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2073 E);
2074 }
2075
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002077 Expr *E =
2078 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002079 return TemplateArgumentLoc(TemplateArgument(E), E);
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregor9d802122011-03-02 17:09:35 +00002082 case TemplateArgument::Template:
2083 case TemplateArgument::TemplateExpansion: {
2084 NestedNameSpecifierLocBuilder Builder;
2085 TemplateName Template = Arg.getAsTemplate();
2086 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002087 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002088 else if (QualifiedTemplateName *QTN =
2089 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002090 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002091
Douglas Gregor9d802122011-03-02 17:09:35 +00002092 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002093 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002094 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002095
2096 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002097 Loc, Loc);
2098 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002099
Douglas Gregorca4686d2011-01-04 23:35:54 +00002100 case TemplateArgument::Expression:
2101 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
Douglas Gregorca4686d2011-01-04 23:35:54 +00002103 case TemplateArgument::Pack:
2104 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106
David Blaikiee4d798f2012-01-20 21:50:17 +00002107 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002108}
2109
2110
2111/// \brief Convert the given deduced template argument and add it to the set of
2112/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002113static bool
2114ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2115 DeducedTemplateArgument Arg,
2116 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002117 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002118 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002119 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002120 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2121 unsigned ArgumentPackIndex) {
2122 // Convert the deduced template argument into a template
2123 // argument that we can check, almost as if the user had written
2124 // the template argument explicitly.
2125 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002126 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002127
2128 // Check the template argument, converting it as necessary.
2129 return S.CheckTemplateArgument(
2130 Param, ArgLoc, Template, Template->getLocation(),
2131 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002132 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002133 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2134 : Sema::CTAK_Deduced)
2135 : Sema::CTAK_Specified);
2136 };
2137
Douglas Gregorca4686d2011-01-04 23:35:54 +00002138 if (Arg.getKind() == TemplateArgument::Pack) {
2139 // This is a template argument pack, so check each of its arguments against
2140 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002141 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002142 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002143 // When converting the deduced template argument, append it to the
2144 // general output list. We need to do this so that the template argument
2145 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002146 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002147 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002148 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2149 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002150 if (P.isNull()) {
2151 // We deduced arguments for some elements of this pack, but not for
2152 // all of them. This happens if we get a conditionally-non-deduced
2153 // context in a pack expansion (such as an overload set in one of the
2154 // arguments).
2155 S.Diag(Param->getLocation(),
2156 diag::err_template_arg_deduced_incomplete_pack)
2157 << Arg << Param;
2158 return true;
2159 }
Richard Smith37acb792016-02-03 20:15:01 +00002160 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002161 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregor51bc5712011-01-05 20:52:18 +00002163 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002164 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Richard Smithdf18ee92016-02-03 20:40:30 +00002167 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002168 // itself, in case that substitution fails.
2169 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002170 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002171 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002172 MultiLevelTemplateArgumentList Args(TemplateArgs);
2173
2174 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2175 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2176 NTTP, Output,
2177 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002178 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002179 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2180 NTTP->getDeclName()).isNull())
2181 return true;
2182 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2183 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2184 TTP, Output,
2185 Template->getSourceRange());
2186 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2187 return true;
2188 }
2189 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002190 }
Richard Smith37acb792016-02-03 20:15:01 +00002191
Douglas Gregorca4686d2011-01-04 23:35:54 +00002192 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002193 Output.push_back(
2194 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002195 return false;
2196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Richard Smith37acb792016-02-03 20:15:01 +00002198 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002199}
2200
Richard Smith1f5be4d2016-12-21 01:10:31 +00002201// FIXME: This should not be a template, but
2202// ClassTemplatePartialSpecializationDecl sadly does not derive from
2203// TemplateDecl.
2204template<typename TemplateDeclT>
2205static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002206 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002207 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2208 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2209 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2210 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2211 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2212
2213 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2214 NamedDecl *Param = TemplateParams->getParam(I);
2215
2216 if (!Deduced[I].isNull()) {
2217 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002218 // We may have had explicitly-specified template arguments for a
2219 // template parameter pack (that may or may not have been extended
2220 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002221 if (Param->isParameterPack() && CurrentInstantiationScope &&
2222 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2223 // Forget the partially-substituted pack; its substitution is now
2224 // complete.
2225 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2226 // We still need to check the argument in case it was extended by
2227 // deduction.
2228 } else {
2229 // We have already fully type-checked and converted this
2230 // argument, because it was explicitly-specified. Just record the
2231 // presence of this argument.
2232 Builder.push_back(Deduced[I]);
2233 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002234 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002235 }
2236
Richard Smith9c0c9862017-01-05 20:27:28 +00002237 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002238 // checked and converted.
2239 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002240 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002241 Info.Param = makeTemplateParameter(Param);
2242 // FIXME: These template arguments are temporary. Free them!
2243 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2244 return Sema::TDK_SubstitutionFailure;
2245 }
2246
2247 continue;
2248 }
2249
2250 // C++0x [temp.arg.explicit]p3:
2251 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2252 // be deduced to an empty sequence of template arguments.
2253 // FIXME: Where did the word "trailing" come from?
2254 if (Param->isTemplateParameterPack()) {
2255 // We may have had explicitly-specified template arguments for this
2256 // template parameter pack. If so, our empty deduction extends the
2257 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2258 const TemplateArgument *ExplicitArgs;
2259 unsigned NumExplicitArgs;
2260 if (CurrentInstantiationScope &&
2261 CurrentInstantiationScope->getPartiallySubstitutedPack(
2262 &ExplicitArgs, &NumExplicitArgs) == Param) {
2263 Builder.push_back(TemplateArgument(
2264 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2265
2266 // Forget the partially-substituted pack; its substitution is now
2267 // complete.
2268 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2269 } else {
2270 // Go through the motions of checking the empty argument pack against
2271 // the parameter pack.
2272 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002273 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2274 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002275 Info.Param = makeTemplateParameter(Param);
2276 // FIXME: These template arguments are temporary. Free them!
2277 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2278 return Sema::TDK_SubstitutionFailure;
2279 }
2280 }
2281 continue;
2282 }
2283
2284 // Substitute into the default template argument, if available.
2285 bool HasDefaultArg = false;
2286 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2287 if (!TD) {
2288 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2289 return Sema::TDK_Incomplete;
2290 }
2291
2292 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2293 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2294 HasDefaultArg);
2295
2296 // If there was no default argument, deduction is incomplete.
2297 if (DefArg.getArgument().isNull()) {
2298 Info.Param = makeTemplateParameter(
2299 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2300 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2301 if (PartialOverloading) break;
2302
2303 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2304 : Sema::TDK_Incomplete;
2305 }
2306
2307 // Check whether we can actually use the default argument.
2308 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2309 TD->getSourceRange().getEnd(), 0, Builder,
2310 Sema::CTAK_Specified)) {
2311 Info.Param = makeTemplateParameter(
2312 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2313 // FIXME: These template arguments are temporary. Free them!
2314 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2315 return Sema::TDK_SubstitutionFailure;
2316 }
2317
2318 // If we get here, we successfully used the default template argument.
2319 }
2320
2321 return Sema::TDK_Success;
2322}
2323
Richard Smith0da6dc42016-12-24 16:40:51 +00002324DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2325 if (auto *DC = dyn_cast<DeclContext>(D))
2326 return DC;
2327 return D->getDeclContext();
2328}
2329
2330template<typename T> struct IsPartialSpecialization {
2331 static constexpr bool value = false;
2332};
2333template<>
2334struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2335 static constexpr bool value = true;
2336};
2337template<>
2338struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2339 static constexpr bool value = true;
2340};
2341
2342/// Complete template argument deduction for a partial specialization.
2343template <typename T>
2344static typename std::enable_if<IsPartialSpecialization<T>::value,
2345 Sema::TemplateDeductionResult>::type
2346FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002347 Sema &S, T *Partial, bool IsPartialOrdering,
2348 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002349 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2350 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002351 // Unevaluated SFINAE context.
2352 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002353 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002354
Richard Smith0da6dc42016-12-24 16:40:51 +00002355 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002356
2357 // C++ [temp.deduct.type]p2:
2358 // [...] or if any template argument remains neither deduced nor
2359 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002360 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002361 if (auto Result = ConvertDeducedTemplateArguments(
2362 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002363 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002364
Douglas Gregor684268d2010-04-29 06:21:43 +00002365 // Form the template argument list from the deduced template arguments.
2366 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002367 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002368
Douglas Gregor684268d2010-04-29 06:21:43 +00002369 Info.reset(DeducedArgumentList);
2370
2371 // Substitute the deduced template arguments into the template
2372 // arguments of the class template partial specialization, and
2373 // verify that the instantiated template arguments are both valid
2374 // and are equivalent to the template arguments originally provided
2375 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002376 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002377 auto *Template = Partial->getSpecializedTemplate();
2378 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2379 Partial->getTemplateArgsAsWritten();
2380 const TemplateArgumentLoc *PartialTemplateArgs =
2381 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002382
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002383 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2384 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002385
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002386 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002387 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2388 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2389 if (ParamIdx >= Partial->getTemplateParameters()->size())
2390 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2391
Richard Smith0da6dc42016-12-24 16:40:51 +00002392 Decl *Param = const_cast<NamedDecl *>(
2393 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002394 Info.Param = makeTemplateParameter(Param);
2395 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2396 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002397 }
2398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002399 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002400 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2401 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002402 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002403
Richard Smith0da6dc42016-12-24 16:40:51 +00002404 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002405 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002406 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002407 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002408 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002409 Info.FirstArg = TemplateArgs[I];
2410 Info.SecondArg = InstArg;
2411 return Sema::TDK_NonDeducedMismatch;
2412 }
2413 }
2414
2415 if (Trap.hasErrorOccurred())
2416 return Sema::TDK_SubstitutionFailure;
2417
2418 return Sema::TDK_Success;
2419}
2420
Richard Smith0e617ec2016-12-27 07:56:27 +00002421/// Complete template argument deduction for a class or variable template,
2422/// when partial ordering against a partial specialization.
2423// FIXME: Factor out duplication with partial specialization version above.
2424Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2425 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2426 const TemplateArgumentList &TemplateArgs,
2427 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2428 TemplateDeductionInfo &Info) {
2429 // Unevaluated SFINAE context.
2430 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2431 Sema::SFINAETrap Trap(S);
2432
2433 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2434
2435 // C++ [temp.deduct.type]p2:
2436 // [...] or if any template argument remains neither deduced nor
2437 // explicitly specified, template argument deduction fails.
2438 SmallVector<TemplateArgument, 4> Builder;
2439 if (auto Result = ConvertDeducedTemplateArguments(
2440 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2441 return Result;
2442
2443 // Check that we produced the correct argument list.
2444 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2445 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2446 TemplateArgument InstArg = Builder[I];
2447 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2448 /*PackExpansionMatchesPack*/true)) {
2449 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2450 Info.FirstArg = TemplateArgs[I];
2451 Info.SecondArg = InstArg;
2452 return Sema::TDK_NonDeducedMismatch;
2453 }
2454 }
2455
2456 if (Trap.hasErrorOccurred())
2457 return Sema::TDK_SubstitutionFailure;
2458
2459 return Sema::TDK_Success;
2460}
2461
2462
Douglas Gregor170bc422009-06-12 22:31:52 +00002463/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002464/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002465/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002466Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002467Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002468 const TemplateArgumentList &TemplateArgs,
2469 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002470 if (Partial->isInvalidDecl())
2471 return TDK_Invalid;
2472
Douglas Gregor170bc422009-06-12 22:31:52 +00002473 // C++ [temp.class.spec.match]p2:
2474 // A partial specialization matches a given actual template
2475 // argument list if the template arguments of the partial
2476 // specialization can be deduced from the actual template argument
2477 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002478
2479 // Unevaluated SFINAE context.
2480 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002481 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002482
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002483 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002484 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002485 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002486 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002487 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002488 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002489 TemplateArgs, Info, Deduced))
2490 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002491
Richard Smith80934652012-07-16 01:09:10 +00002492 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002493 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2494 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002495 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002496 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002497
Douglas Gregore1416332009-06-14 08:02:22 +00002498 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002499 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002500
Richard Smith87d263e2016-12-25 08:05:23 +00002501 return ::FinishTemplateArgumentDeduction(
2502 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002503}
Douglas Gregor91772d12009-06-13 00:26:55 +00002504
Larisse Voufo39a1e502013-08-06 01:03:05 +00002505/// \brief Perform template argument deduction to determine whether
2506/// the given template arguments match the given variable template
2507/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508Sema::TemplateDeductionResult
2509Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2510 const TemplateArgumentList &TemplateArgs,
2511 TemplateDeductionInfo &Info) {
2512 if (Partial->isInvalidDecl())
2513 return TDK_Invalid;
2514
2515 // C++ [temp.class.spec.match]p2:
2516 // A partial specialization matches a given actual template
2517 // argument list if the template arguments of the partial
2518 // specialization can be deduced from the actual template argument
2519 // list (14.8.2).
2520
2521 // Unevaluated SFINAE context.
2522 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2523 SFINAETrap Trap(*this);
2524
2525 SmallVector<DeducedTemplateArgument, 4> Deduced;
2526 Deduced.resize(Partial->getTemplateParameters()->size());
2527 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2528 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2529 TemplateArgs, Info, Deduced))
2530 return Result;
2531
2532 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002533 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2534 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002535 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536 return TDK_InstantiationDepth;
2537
2538 if (Trap.hasErrorOccurred())
2539 return Sema::TDK_SubstitutionFailure;
2540
Richard Smith87d263e2016-12-25 08:05:23 +00002541 return ::FinishTemplateArgumentDeduction(
2542 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543}
2544
Douglas Gregorfc516c92009-06-26 23:27:24 +00002545/// \brief Determine whether the given type T is a simple-template-id type.
2546static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002547 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002548 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregorfc516c92009-06-26 23:27:24 +00002551 return false;
2552}
Douglas Gregor9b146582009-07-08 20:55:45 +00002553
2554/// \brief Substitute the explicitly-provided template arguments into the
2555/// given function template according to C++ [temp.arg.explicit].
2556///
2557/// \param FunctionTemplate the function template into which the explicit
2558/// template arguments will be substituted.
2559///
James Dennett634962f2012-06-14 21:40:34 +00002560/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002561/// arguments.
2562///
Mike Stump11289f42009-09-09 15:08:12 +00002563/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002564/// with the converted and checked explicit template arguments.
2565///
Mike Stump11289f42009-09-09 15:08:12 +00002566/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002567/// parameters.
2568///
2569/// \param FunctionType if non-NULL, the result type of the function template
2570/// will also be instantiated and the pointed-to value will be updated with
2571/// the instantiated function type.
2572///
2573/// \param Info if substitution fails for any reason, this object will be
2574/// populated with more information about the failure.
2575///
2576/// \returns TDK_Success if substitution was successful, or some failure
2577/// condition.
2578Sema::TemplateDeductionResult
2579Sema::SubstituteExplicitTemplateArguments(
2580 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002581 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002582 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2583 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002584 QualType *FunctionType,
2585 TemplateDeductionInfo &Info) {
2586 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2587 TemplateParameterList *TemplateParams
2588 = FunctionTemplate->getTemplateParameters();
2589
John McCall6b51f282009-11-23 01:53:49 +00002590 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002591 // No arguments to substitute; just copy over the parameter types and
2592 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002593 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002594 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002595
Douglas Gregor9b146582009-07-08 20:55:45 +00002596 if (FunctionType)
2597 *FunctionType = Function->getType();
2598 return TDK_Success;
2599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Eli Friedman77dcc722012-02-08 03:07:05 +00002601 // Unevaluated SFINAE context.
2602 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002603 SFINAETrap Trap(*this);
2604
Douglas Gregor9b146582009-07-08 20:55:45 +00002605 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002606 // Template arguments that are present shall be specified in the
2607 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002608 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002609 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002610 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002611
2612 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002613 // explicitly-specified template arguments against this function template,
2614 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002615 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002616 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2617 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002618 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2619 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002620 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002621 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002622
Douglas Gregor9b146582009-07-08 20:55:45 +00002623 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002624 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002625 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002626 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002627 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002628 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002629 if (Index >= TemplateParams->size())
2630 Index = TemplateParams->size() - 1;
2631 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002632 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002633 }
Mike Stump11289f42009-09-09 15:08:12 +00002634
Douglas Gregor9b146582009-07-08 20:55:45 +00002635 // Form the template argument list from the explicitly-specified
2636 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002637 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002638 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002639 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002640
John McCall036855a2010-10-12 19:40:14 +00002641 // Template argument deduction and the final substitution should be
2642 // done in the context of the templated declaration. Explicit
2643 // argument substitution, on the other hand, needs to happen in the
2644 // calling context.
2645 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2646
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002647 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002648 // note that the template argument pack is partially substituted and record
2649 // the explicit template arguments. They'll be used as part of deduction
2650 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002651 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2652 const TemplateArgument &Arg = Builder[I];
2653 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002654 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002656 Arg.pack_begin(),
2657 Arg.pack_size());
2658 break;
2659 }
2660 }
2661
Richard Smith5e580292012-02-10 09:58:53 +00002662 const FunctionProtoType *Proto
2663 = Function->getType()->getAs<FunctionProtoType>();
2664 assert(Proto && "Function template does not have a prototype?");
2665
Richard Smith70b13042015-01-09 01:19:56 +00002666 // Isolate our substituted parameters from our caller.
2667 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2668
John McCallc8e321d2016-03-01 02:09:25 +00002669 ExtParameterInfoBuilder ExtParamInfos;
2670
Douglas Gregor9b146582009-07-08 20:55:45 +00002671 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002672 // explicitly-specified template arguments. If the function has a trailing
2673 // return type, substitute it after the arguments to ensure we substitute
2674 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002675 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002676 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002677 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002678 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002679 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002680 return TDK_SubstitutionFailure;
2681 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002682
Richard Smith5e580292012-02-10 09:58:53 +00002683 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002684 QualType ResultType;
2685 {
2686 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002687 // If a declaration declares a member function or member function
2688 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002689 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002690 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002691 // declarator.
2692 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002693 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2695 ThisContext = Method->getParent();
2696 ThisTypeQuals = Method->getTypeQualifiers();
2697 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002698
Douglas Gregor3024f072012-04-16 07:05:22 +00002699 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002700 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002701
2702 ResultType =
2703 SubstType(Proto->getReturnType(),
2704 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2705 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002706 if (ResultType.isNull() || Trap.hasErrorOccurred())
2707 return TDK_SubstitutionFailure;
2708 }
John McCallc8e321d2016-03-01 02:09:25 +00002709
Richard Smith5e580292012-02-10 09:58:53 +00002710 // Instantiate the types of each of the function parameters given the
2711 // explicitly-specified template arguments if we didn't do so earlier.
2712 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002713 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002714 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002715 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002716 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002717 return TDK_SubstitutionFailure;
2718
Douglas Gregor9b146582009-07-08 20:55:45 +00002719 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002720 auto EPI = Proto->getExtProtoInfo();
2721 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002722 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002723 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002724 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002725 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002726 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2727 return TDK_SubstitutionFailure;
2728 }
Mike Stump11289f42009-09-09 15:08:12 +00002729
Douglas Gregor9b146582009-07-08 20:55:45 +00002730 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002731 // Trailing template arguments that can be deduced (14.8.2) may be
2732 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002733 // template arguments can be deduced, they may all be omitted; in this
2734 // case, the empty template argument list <> itself may also be omitted.
2735 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002736 // Take all of the explicitly-specified arguments and put them into
2737 // the set of deduced template arguments. Explicitly-specified
2738 // parameter packs, however, will be set to NULL since the deduction
2739 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002740 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002741 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2742 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2743 if (Arg.getKind() == TemplateArgument::Pack)
2744 Deduced.push_back(DeducedTemplateArgument());
2745 else
2746 Deduced.push_back(Arg);
2747 }
Mike Stump11289f42009-09-09 15:08:12 +00002748
Douglas Gregor9b146582009-07-08 20:55:45 +00002749 return TDK_Success;
2750}
2751
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002752/// \brief Check whether the deduced argument type for a call to a function
2753/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002754static bool
2755CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002756 QualType DeducedA) {
2757 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002758
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002759 QualType A = OriginalArg.OriginalArgType;
2760 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002761
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002762 // Check for type equality (top-level cv-qualifiers are ignored).
2763 if (Context.hasSameUnqualifiedType(A, DeducedA))
2764 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002765
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002766 // Strip off references on the argument types; they aren't needed for
2767 // the following checks.
2768 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2769 DeducedA = DeducedARef->getPointeeType();
2770 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2771 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002772
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002773 // C++ [temp.deduct.call]p4:
2774 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002775 // - If the original P is a reference type, the deduced A (i.e., the
2776 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002777 // the transformed A.
2778 if (const ReferenceType *OriginalParamRef
2779 = OriginalParamType->getAs<ReferenceType>()) {
2780 // We don't want to keep the reference around any more.
2781 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002782
Richard Smith1be59c52016-10-22 01:32:19 +00002783 // FIXME: Resolve core issue (no number yet): if the original P is a
2784 // reference type and the transformed A is function type "noexcept F",
2785 // the deduced A can be F.
2786 QualType Tmp;
2787 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2788 return false;
2789
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002790 Qualifiers AQuals = A.getQualifiers();
2791 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002792
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002793 // Under Objective-C++ ARC, the deduced type may have implicitly
2794 // been given strong or (when dealing with a const reference)
2795 // unsafe_unretained lifetime. If so, update the original
2796 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002797 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002798 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2799 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2800 (DeducedAQuals.hasConst() &&
2801 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2802 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002803 }
2804
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002805 if (AQuals == DeducedAQuals) {
2806 // Qualifiers match; there's nothing to do.
2807 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002808 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002809 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 // Qualifiers are compatible, so have the argument type adopt the
2811 // deduced argument type's qualifiers as if we had performed the
2812 // qualification conversion.
2813 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2814 }
2815 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002816
2817 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002818 // type that can be converted to the deduced A via a function pointer
2819 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002820 //
Richard Smith1be59c52016-10-22 01:32:19 +00002821 // Also allow conversions which merely strip __attribute__((noreturn)) from
2822 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002823 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002824 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002825 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002826 (S.IsQualificationConversion(A, DeducedA, false,
2827 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002828 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002829 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002830
Simon Pilgrim728134c2016-08-12 11:43:57 +00002831 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002832 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002833 // [...] Likewise, if P is a pointer to a class of the form
2834 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002835 // derived class pointed to by the deduced A.
2836 if (const PointerType *OriginalParamPtr
2837 = OriginalParamType->getAs<PointerType>()) {
2838 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2839 if (const PointerType *APtr = A->getAs<PointerType>()) {
2840 if (A->getPointeeType()->isRecordType()) {
2841 OriginalParamType = OriginalParamPtr->getPointeeType();
2842 DeducedA = DeducedAPtr->getPointeeType();
2843 A = APtr->getPointeeType();
2844 }
2845 }
2846 }
2847 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002848
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002849 if (Context.hasSameUnqualifiedType(A, DeducedA))
2850 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002851
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002852 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002853 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002854 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002855
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002856 return true;
2857}
2858
Mike Stump11289f42009-09-09 15:08:12 +00002859/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002860/// checking the deduced template arguments for completeness and forming
2861/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002862///
2863/// \param OriginalCallArgs If non-NULL, the original call arguments against
2864/// which the deduced argument types should be compared.
Renato Golindad96d62017-01-02 11:15:42 +00002865Sema::TemplateDeductionResult
2866Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2867 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2868 unsigned NumExplicitlySpecified,
2869 FunctionDecl *&Specialization,
2870 TemplateDeductionInfo &Info,
2871 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2872 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002873 // Unevaluated SFINAE context.
2874 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002875 SFINAETrap Trap(*this);
2876
Douglas Gregor9b146582009-07-08 20:55:45 +00002877 // Enter a new template instantiation context while we instantiate the
2878 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002879 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002880 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2881 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002882 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2883 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002884 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002885 return TDK_InstantiationDepth;
2886
John McCalle23b8712010-04-29 01:18:58 +00002887 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002888
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002889 // C++ [temp.deduct.type]p2:
2890 // [...] or if any template argument remains neither deduced nor
2891 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002892 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002893 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002894 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002895 CurrentInstantiationScope, NumExplicitlySpecified,
2896 PartialOverloading))
2897 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002898
2899 // Form the template argument list from the deduced template arguments.
2900 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002901 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002902 Info.reset(DeducedArgumentList);
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002905 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002906 DeclContext *Owner = FunctionTemplate->getDeclContext();
2907 if (FunctionTemplate->getFriendObjectKind())
2908 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002909 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002910 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002911 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002912 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002913 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002916 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917
Mike Stump11289f42009-09-09 15:08:12 +00002918 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002919 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002920 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2921 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002922 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002924 // There may have been an error that did not prevent us from constructing a
2925 // declaration. Mark the declaration invalid and return with a substitution
2926 // failure.
2927 if (Trap.hasErrorOccurred()) {
2928 Specialization->setInvalidDecl(true);
2929 return TDK_SubstitutionFailure;
2930 }
2931
Douglas Gregore65aacb2011-06-16 16:50:48 +00002932 if (OriginalCallArgs) {
2933 // C++ [temp.deduct.call]p4:
2934 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002935 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002936 // is transformed as described above). [...]
2937 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2938 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002939 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002940
Douglas Gregore65aacb2011-06-16 16:50:48 +00002941 if (ParamIdx >= Specialization->getNumParams())
2942 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002943
Douglas Gregore65aacb2011-06-16 16:50:48 +00002944 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002945 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2946 Info.FirstArg = TemplateArgument(DeducedA);
2947 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2948 Info.CallArgIndex = OriginalArg.ArgIdx;
2949 return TDK_DeducedMismatch;
2950 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002951 }
2952 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002953
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002954 // If we suppressed any diagnostics while performing template argument
2955 // deduction, and if we haven't already instantiated this declaration,
2956 // keep track of these diagnostics. They'll be emitted if this specialization
2957 // is actually used.
2958 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002959 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002960 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2961 if (Pos == SuppressedDiagnostics.end())
2962 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2963 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002965
Mike Stump11289f42009-09-09 15:08:12 +00002966 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002967}
2968
John McCall8d08b9b2010-08-27 09:08:28 +00002969/// Gets the type of a function for template-argument-deducton
2970/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002971static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002972 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002973 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002974 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002975 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002976 return QualType();
2977
John McCallc1f69982010-02-02 02:21:27 +00002978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002979 if (Method->isInstance()) {
2980 // An instance method that's referenced in a form that doesn't
2981 // look like a member pointer is just invalid.
2982 if (!R.HasFormOfMemberPointer) return QualType();
2983
Richard Smith2a7d4812013-05-04 07:00:32 +00002984 return S.Context.getMemberPointerType(Fn->getType(),
2985 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002986 }
2987
2988 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002989 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002990}
2991
2992/// Apply the deduction rules for overload sets.
2993///
2994/// \return the null type if this argument should be treated as an
2995/// undeduced context
2996static QualType
2997ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002998 Expr *Arg, QualType ParamType,
2999 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000
John McCall8d08b9b2010-08-27 09:08:28 +00003001 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003002
John McCall8d08b9b2010-08-27 09:08:28 +00003003 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003004
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003005 // C++0x [temp.deduct.call]p4
3006 unsigned TDF = 0;
3007 if (ParamWasReference)
3008 TDF |= TDF_ParamWithReferenceType;
3009 if (R.IsAddressOfOperand)
3010 TDF |= TDF_IgnoreQualifiers;
3011
John McCallc1f69982010-02-02 02:21:27 +00003012 // C++0x [temp.deduct.call]p6:
3013 // When P is a function type, pointer to function type, or pointer
3014 // to member function type:
3015
3016 if (!ParamType->isFunctionType() &&
3017 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003018 !ParamType->isMemberFunctionPointerType()) {
3019 if (Ovl->hasExplicitTemplateArgs()) {
3020 // But we can still look for an explicit specialization.
3021 if (FunctionDecl *ExplicitSpec
3022 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003023 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003024 }
John McCallc1f69982010-02-02 02:21:27 +00003025
George Burgess IVcc2f3552016-03-19 21:51:45 +00003026 DeclAccessPair DAP;
3027 if (FunctionDecl *Viable =
3028 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3029 return GetTypeOfFunction(S, R, Viable);
3030
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003031 return QualType();
3032 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003033
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003034 // Gather the explicit template arguments, if any.
3035 TemplateArgumentListInfo ExplicitTemplateArgs;
3036 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003037 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003038 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003039 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3040 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003041 NamedDecl *D = (*I)->getUnderlyingDecl();
3042
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003043 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3044 // - If the argument is an overload set containing one or more
3045 // function templates, the parameter is treated as a
3046 // non-deduced context.
3047 if (!Ovl->hasExplicitTemplateArgs())
3048 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003049
3050 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003051 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003052 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003053 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3054 Specialization, Info))
3055 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003056
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003057 D = Specialization;
3058 }
John McCallc1f69982010-02-02 02:21:27 +00003059
3060 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003061 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003062 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003063
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003064 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003066 ArgType->isFunctionType())
3067 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003068
John McCallc1f69982010-02-02 02:21:27 +00003069 // - If the argument is an overload set (not containing function
3070 // templates), trial argument deduction is attempted using each
3071 // of the members of the set. If deduction succeeds for only one
3072 // of the overload set members, that member is used as the
3073 // argument value for the deduction. If deduction succeeds for
3074 // more than one member of the overload set the parameter is
3075 // treated as a non-deduced context.
3076
3077 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3078 // Type deduction is done independently for each P/A pair, and
3079 // the deduced template argument values are then combined.
3080 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003081 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003082 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003083 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003084 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003085 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3086 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003087 if (Result) continue;
3088 if (!Match.isNull()) return QualType();
3089 Match = ArgType;
3090 }
3091
3092 return Match;
3093}
3094
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003096/// described in C++ [temp.deduct.call].
3097///
3098/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003099/// argument deduction based on this P/A pair because the argument is an
3100/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003101static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3102 TemplateParameterList *TemplateParams,
3103 QualType &ParamType,
3104 QualType &ArgType,
3105 Expr *Arg,
3106 unsigned &TDF) {
3107 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003108 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003109 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003110 if (ParamType.hasQualifiers())
3111 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003112
3113 // [...] If P is a reference type, the type referred to by P is
3114 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003115 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003116 if (ParamRefType)
3117 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003118
Nathan Sidwell96090022015-01-16 15:20:14 +00003119 // Overload sets usually make this parameter an undeduced context,
3120 // but there are sometimes special circumstances. Typically
3121 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003122 if (ArgType == S.Context.OverloadTy) {
3123 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3124 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003125 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003126 if (ArgType.isNull())
3127 return true;
3128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003129
Douglas Gregor7825bf32011-01-06 22:09:01 +00003130 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003131 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003132 if (ArgType->isIncompleteArrayType()) {
3133 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003134 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003135 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003136
Douglas Gregor7825bf32011-01-06 22:09:01 +00003137 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003138 // If P is an rvalue reference to a cv-unqualified template
3139 // parameter and the argument is an lvalue, the type "lvalue
3140 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003141 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003142 !ParamType.getQualifiers() &&
3143 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003144 Arg->isLValue())
3145 ArgType = S.Context.getLValueReferenceType(ArgType);
3146 } else {
3147 // C++ [temp.deduct.call]p2:
3148 // If P is not a reference type:
3149 // - If A is an array type, the pointer type produced by the
3150 // array-to-pointer standard conversion (4.2) is used in place of
3151 // A for type deduction; otherwise,
3152 if (ArgType->isArrayType())
3153 ArgType = S.Context.getArrayDecayedType(ArgType);
3154 // - If A is a function type, the pointer type produced by the
3155 // function-to-pointer standard conversion (4.3) is used in place
3156 // of A for type deduction; otherwise,
3157 else if (ArgType->isFunctionType())
3158 ArgType = S.Context.getPointerType(ArgType);
3159 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003160 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003161 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003162 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003163 }
3164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Douglas Gregor7825bf32011-01-06 22:09:01 +00003166 // C++0x [temp.deduct.call]p4:
3167 // In general, the deduction process attempts to find template argument
3168 // values that will make the deduced A identical to A (after the type A
3169 // is transformed as described above). [...]
3170 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 // - If the original P is a reference type, the deduced A (i.e., the
3173 // type referred to by the reference) can be more cv-qualified than
3174 // the transformed A.
3175 if (ParamRefType)
3176 TDF |= TDF_ParamWithReferenceType;
3177 // - The transformed A can be another pointer or pointer to member
3178 // type that can be converted to the deduced A via a qualification
3179 // conversion (4.4).
3180 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3181 ArgType->isObjCObjectPointerType())
3182 TDF |= TDF_IgnoreQualifiers;
3183 // - If P is a class and P has the form simple-template-id, then the
3184 // transformed A can be a derived class of the deduced A. Likewise,
3185 // if P is a pointer to a class of the form simple-template-id, the
3186 // transformed A can be a pointer to a derived class pointed to by
3187 // the deduced A.
3188 if (isSimpleTemplateIdType(ParamType) ||
3189 (isa<PointerType>(ParamType) &&
3190 isSimpleTemplateIdType(
3191 ParamType->getAs<PointerType>()->getPointeeType())))
3192 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor7825bf32011-01-06 22:09:01 +00003194 return false;
3195}
3196
Nico Weberc153d242014-07-28 00:02:09 +00003197static bool
3198hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3199 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003200
Richard Smith707eab62017-01-05 04:08:31 +00003201static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Hubert Tong3280b332015-06-25 00:25:49 +00003202 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3203 Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003204 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3205 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3206 Optional<unsigned> ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003207
3208/// \brief Attempt template argument deduction from an initializer list
3209/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003210static Sema::TemplateDeductionResult DeduceFromInitializerList(
3211 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3212 InitListExpr *ILE, TemplateDeductionInfo &Info,
3213 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3214 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003215 // C++ [temp.deduct.call]p1: (CWG 1591)
3216 // If removing references and cv-qualifiers from P gives
3217 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3218 // a non-empty initializer list, then deduction is performed instead for
3219 // each element of the initializer list, taking P0 as a function template
3220 // parameter type and the initializer element as its argument
3221 //
Richard Smith707eab62017-01-05 04:08:31 +00003222 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003223 if (!ILE->getNumInits())
3224 return Sema::TDK_Success;
3225
Richard Smitha7d5ec92017-01-04 19:47:19 +00003226 QualType ElTy;
3227 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3228 if (ArrTy)
3229 ElTy = ArrTy->getElementType();
3230 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3231 // Otherwise, an initializer list argument causes the parameter to be
3232 // considered a non-deduced context
3233 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003234 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003235
Faisal Valif6dfdb32015-12-10 05:36:39 +00003236 // Deduction only needs to be done for dependent types.
3237 if (ElTy->isDependentType()) {
3238 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003239 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3240 S, TemplateParams, ElTy, E, Info, Deduced, OriginalCallArgs, None,
3241 TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003242 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003243 }
3244 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003245
3246 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3247 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003248 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003249 // Determine the array bound is something we can deduce.
3250 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003251 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003252 // We can perform template argument deduction for the given non-type
3253 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003254 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3255 ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003256 if (auto Result = DeduceNonTypeTemplateArgument(
3257 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3258 /*ArrayBound=*/true, Info, Deduced))
3259 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003260 }
3261 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003262
3263 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003264}
3265
Richard Smith707eab62017-01-05 04:08:31 +00003266/// \brief Perform template argument deduction per [temp.deduct.call] for a
3267/// single parameter / argument pair.
3268static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3269 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3270 Expr *Arg, TemplateDeductionInfo &Info,
3271 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3272 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3273 Optional<unsigned> ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003274 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003275 QualType OrigParamType = ParamType;
3276
3277 // If P is a reference type [...]
3278 // If P is a cv-qualified type [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003279 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith363ae812017-01-04 22:03:59 +00003280 ArgType, Arg, TDF))
3281 return Sema::TDK_Success;
3282
Richard Smith707eab62017-01-05 04:08:31 +00003283 // If [...] the argument is a non-empty initializer list [...]
3284 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3285 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3286 Deduced, OriginalCallArgs, TDF);
3287
3288 // [...] the deduction process attempts to find template argument values
3289 // that will make the deduced A identical to A
3290 //
3291 // Keep track of the argument type and corresponding parameter index,
3292 // so we can check for compatibility between the deduced A and A.
3293 //
3294 // FIXME: We are supposed to perform this check for the P/A pairs we extract
3295 // from the initializer list case too.
3296 if (ArgIdx)
3297 OriginalCallArgs.push_back(
3298 Sema::OriginalCallArg(OrigParamType, *ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003300 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003301}
3302
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303/// \brief Perform template argument deduction from a function call
3304/// (C++ [temp.deduct.call]).
3305///
3306/// \param FunctionTemplate the function template for which we are performing
3307/// template argument deduction.
3308///
James Dennett18348b62012-06-22 08:52:37 +00003309/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003310/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003311///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312/// \param Args the function call arguments
3313///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003315/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003316/// template argument deduction.
3317///
3318/// \param Info the argument will be updated to provide additional information
3319/// about template argument deduction.
3320///
3321/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003322Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3323 FunctionTemplateDecl *FunctionTemplate,
3324 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003325 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Renato Golindad96d62017-01-02 11:15:42 +00003326 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003327 if (FunctionTemplate->isInvalidDecl())
3328 return TDK_Invalid;
3329
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003330 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003331 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003332
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003333 // C++ [temp.deduct.call]p1:
3334 // Template argument deduction is done by comparing each function template
3335 // parameter type (call it P) with the type of the corresponding argument
3336 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003337 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003338 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003339 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003340 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003341 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003342 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003343 if (Proto->isTemplateVariadic())
3344 /* Do nothing */;
3345 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003346 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003348 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregor89026b52009-06-30 23:57:56 +00003351 // The types of the parameters from which we will perform template argument
3352 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003353 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 TemplateParameterList *TemplateParams
3355 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356 SmallVector<DeducedTemplateArgument, 4> Deduced;
3357 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003358 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003359 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003360 TemplateDeductionResult Result =
3361 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003362 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003363 Deduced,
3364 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003365 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003366 Info);
3367 if (Result)
3368 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003369
3370 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003371 } else {
3372 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003373 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003374 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3375 }
Mike Stump11289f42009-09-09 15:08:12 +00003376
Richard Smitha7d5ec92017-01-04 19:47:19 +00003377 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3378
3379 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3380 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003381 // C++ [demp.deduct.call]p1: (DR1391)
3382 // Template argument deduction is done by comparing each function template
3383 // parameter that contains template-parameters that participate in
3384 // template argument deduction ...
Richard Smitha7d5ec92017-01-04 19:47:19 +00003385 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3386 return Sema::TDK_Success;
3387
Richard Smith707eab62017-01-05 04:08:31 +00003388 // ... with the type of the corresponding argument
3389 return DeduceTemplateArgumentsFromCallArgument(
3390 *this, TemplateParams, ParamType, Args[ArgIdx], Info, Deduced,
3391 OriginalCallArgs, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003392 };
3393
Douglas Gregor89026b52009-06-30 23:57:56 +00003394 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003395 Deduced.resize(TemplateParams->size());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003396 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003397 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003398 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003399
Richard Smitha7d5ec92017-01-04 19:47:19 +00003400 const PackExpansionType *ParamExpansion =
3401 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003402 if (!ParamExpansion) {
3403 // Simple case: matching a function parameter to a function argument.
3404 if (ArgIdx >= CheckArgs)
3405 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406
Richard Smitha7d5ec92017-01-04 19:47:19 +00003407 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Douglas Gregor7825bf32011-01-06 22:09:01 +00003410 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Douglas Gregor7825bf32011-01-06 22:09:01 +00003413 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414 // For a function parameter pack that occurs at the end of the
3415 // parameter-declaration-list, the type A of each remaining argument of
3416 // the call is compared with the type P of the declarator-id of the
3417 // function parameter pack. Each comparison deduces template arguments
3418 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003419 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003421 // the parameter pack is a non-deduced context.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003422 // FIXME: This does not say that subsequent parameters are also non-deduced.
3423 // See also DR1388 / DR1399, which effectively says we should keep deducing
3424 // after the pack.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003425 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003426 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Douglas Gregor7825bf32011-01-06 22:09:01 +00003428 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003429 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3430 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Richard Smitha7d5ec92017-01-04 19:47:19 +00003432 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx)
3433 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3434 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregor7825bf32011-01-06 22:09:01 +00003436 // Build argument packs for each of the parameter packs expanded by this
3437 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003438 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003440
Douglas Gregor7825bf32011-01-06 22:09:01 +00003441 // After we've matching against a parameter pack, we're done.
3442 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003443 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003444
Mike Stump11289f42009-09-09 15:08:12 +00003445 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003446 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003447 Info, &OriginalCallArgs,
Renato Golindad96d62017-01-02 11:15:42 +00003448 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003449}
3450
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003451QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003452 QualType FunctionType,
3453 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003454 if (ArgFunctionType.isNull())
3455 return ArgFunctionType;
3456
3457 const FunctionProtoType *FunctionTypeP =
3458 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003459 const FunctionProtoType *ArgFunctionTypeP =
3460 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003461
3462 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3463 bool Rebuild = false;
3464
3465 CallingConv CC = FunctionTypeP->getCallConv();
3466 if (EPI.ExtInfo.getCC() != CC) {
3467 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3468 Rebuild = true;
3469 }
3470
3471 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3472 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3473 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3474 Rebuild = true;
3475 }
3476
3477 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3478 ArgFunctionTypeP->hasExceptionSpec())) {
3479 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3480 Rebuild = true;
3481 }
3482
3483 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003484 return ArgFunctionType;
3485
Richard Smithbaa47832016-12-01 02:11:49 +00003486 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3487 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003488}
3489
Douglas Gregor9b146582009-07-08 20:55:45 +00003490/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003491/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3492/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003493///
3494/// \param FunctionTemplate the function template for which we are performing
3495/// template argument deduction.
3496///
James Dennett18348b62012-06-22 08:52:37 +00003497/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003498/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003499///
3500/// \param ArgFunctionType the function type that will be used as the
3501/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003502/// function template's function type. This type may be NULL, if there is no
3503/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003504///
3505/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003506/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003507/// template argument deduction.
3508///
3509/// \param Info the argument will be updated to provide additional information
3510/// about template argument deduction.
3511///
Richard Smithbaa47832016-12-01 02:11:49 +00003512/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3513/// the address of a function template per [temp.deduct.funcaddr] and
3514/// [over.over]. If \c false, we are looking up a function template
3515/// specialization based on its signature, per [temp.deduct.decl].
3516///
Douglas Gregor9b146582009-07-08 20:55:45 +00003517/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003518Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3519 FunctionTemplateDecl *FunctionTemplate,
3520 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3521 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3522 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003523 if (FunctionTemplate->isInvalidDecl())
3524 return TDK_Invalid;
3525
Douglas Gregor9b146582009-07-08 20:55:45 +00003526 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3527 TemplateParameterList *TemplateParams
3528 = FunctionTemplate->getTemplateParameters();
3529 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003530
3531 // When taking the address of a function, we require convertibility of
3532 // the resulting function type. Otherwise, we allow arbitrary mismatches
3533 // of calling convention, noreturn, and noexcept.
3534 if (!IsAddressOfFunction)
3535 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3536 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003537
Douglas Gregor9b146582009-07-08 20:55:45 +00003538 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003539 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003540 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003541 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003542 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003543 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003544 if (TemplateDeductionResult Result
3545 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003546 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003547 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003548 &FunctionType, Info))
3549 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003550
3551 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003552 }
3553
Eli Friedman77dcc722012-02-08 03:07:05 +00003554 // Unevaluated SFINAE context.
3555 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003556 SFINAETrap Trap(*this);
3557
John McCallc1f69982010-02-02 02:21:27 +00003558 Deduced.resize(TemplateParams->size());
3559
Richard Smith2a7d4812013-05-04 07:00:32 +00003560 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003561 // type so that we treat it as a non-deduced context in what follows. If we
3562 // are looking up by signature, the signature type should also have a deduced
3563 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003564 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003565 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003566 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003567 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003568 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003569 }
3570
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003571 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003572 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003573 if (IsAddressOfFunction)
3574 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003575 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003576 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003577 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003578 FunctionType, ArgFunctionType,
3579 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003580 return Result;
3581 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003582
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003584 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3585 NumExplicitlySpecified,
3586 Specialization, Info))
3587 return Result;
3588
Richard Smith2a7d4812013-05-04 07:00:32 +00003589 // If the function has a deduced return type, deduce it now, so we can check
3590 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003591 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003592 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003593 DeduceReturnType(Specialization, Info.getLocation(), false))
3594 return TDK_MiscellaneousDeductionFailure;
3595
Richard Smith9095e5b2016-11-01 01:31:23 +00003596 // If the function has a dependent exception specification, resolve it now,
3597 // so we can check that the exception specification matches.
3598 auto *SpecializationFPT =
3599 Specialization->getType()->castAs<FunctionProtoType>();
3600 if (getLangOpts().CPlusPlus1z &&
3601 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3602 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3603 return TDK_MiscellaneousDeductionFailure;
3604
Richard Smithbaa47832016-12-01 02:11:49 +00003605 // Adjust the exception specification of the argument again to match the
3606 // substituted and resolved type we just formed. (Calling convention and
3607 // noreturn can't be dependent, so we don't actually need this for them
3608 // right now.)
3609 QualType SpecializationType = Specialization->getType();
3610 if (!IsAddressOfFunction)
3611 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3612 /*AdjustExceptionSpec*/true);
3613
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003614 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003615 // specialization with respect to arguments of compatible pointer to function
3616 // types, template argument deduction fails.
3617 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003618 if (IsAddressOfFunction &&
3619 !isSameOrCompatibleFunctionType(
3620 Context.getCanonicalType(SpecializationType),
3621 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003622 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003623
3624 if (!IsAddressOfFunction &&
3625 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003626 return TDK_MiscellaneousDeductionFailure;
3627 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003628
3629 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003630}
3631
Simon Pilgrim728134c2016-08-12 11:43:57 +00003632/// \brief Given a function declaration (e.g. a generic lambda conversion
3633/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003634/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3635/// to replace 'auto' with and not the actual result type you want
3636/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003637static inline void
3638SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003639 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003640 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003641 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003642 assert(AutoResultType->getContainedAutoType());
3643 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003644 TypeToReplaceAutoWith);
3645 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3646}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003647
Simon Pilgrim728134c2016-08-12 11:43:57 +00003648/// \brief Given a specialized conversion operator of a generic lambda
3649/// create the corresponding specializations of the call operator and
3650/// the static-invoker. If the return type of the call operator is auto,
3651/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003652/// return type of the destination function ptr.
3653
Simon Pilgrim728134c2016-08-12 11:43:57 +00003654static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003655SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3656 CXXConversionDecl *ConversionSpecialized,
3657 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3658 QualType ReturnTypeOfDestFunctionPtr,
3659 TemplateDeductionInfo &TDInfo,
3660 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003661
Faisal Vali2b3a3012013-10-24 23:40:02 +00003662 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003663 assert(LambdaClass && LambdaClass->isGenericLambda());
3664
Faisal Vali2b3a3012013-10-24 23:40:02 +00003665 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003666 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003667 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003668 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003669
3670 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003671 CallOpGeneric->getDescribedFunctionTemplate();
3672
Craig Topperc3ec1492014-05-26 06:22:03 +00003673 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003674 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003675 // generic lambda's call operator.
3676 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003677 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3678 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003679 0, CallOpSpecialized, TDInfo))
3680 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003681
Faisal Vali2b3a3012013-10-24 23:40:02 +00003682 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003683 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3684 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003685 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 CallOpSpecialized->getPointOfInstantiation(),
3687 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003688
Faisal Vali2b3a3012013-10-24 23:40:02 +00003689 // Check to see if the return type of the destination ptr-to-function
3690 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003691 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003692 ReturnTypeOfDestFunctionPtr))
3693 return Sema::TDK_NonDeducedMismatch;
3694 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003695 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003696 // specialized our corresponding call operator, we are ready to
3697 // specialize the static invoker with the deduced arguments of our
3698 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003699 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003700 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3701 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3702
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003703#ifndef NDEBUG
3704 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3705#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003706 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003708 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003709 "If the call operator succeeded so should the invoker!");
3710 // Set the result type to match the corresponding call operator
3711 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003712 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3713 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003715 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716 // to substitute into the 'auto' of the invoker and conversion
3717 // function.
3718 // For e.g.
3719 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3720 // We don't want to subst 'int*' into 'auto' to get int**.
3721
Alp Toker314cc812014-01-25 16:55:45 +00003722 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3723 ->getContainedAutoType()
3724 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003725 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3726 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003727 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003728 TypeToReplaceAutoWith, S);
3729 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003730
Faisal Vali2b3a3012013-10-24 23:40:02 +00003731 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003733 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003734 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3736 getType().getTypePtr()->castAs<FunctionProtoType>();
3737 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3738 EPI.TypeQuals = 0;
3739 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003740 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003741 return Sema::TDK_Success;
3742}
Douglas Gregor05155d82009-08-21 23:19:43 +00003743/// \brief Deduce template arguments for a templated conversion
3744/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3745/// conversion function template specialization.
3746Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003747Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003748 QualType ToType,
3749 CXXConversionDecl *&Specialization,
3750 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003751 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003752 return TDK_Invalid;
3753
Faisal Vali2b3a3012013-10-24 23:40:02 +00003754 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003755 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3756
Faisal Vali2b3a3012013-10-24 23:40:02 +00003757 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003758
3759 // Canonicalize the types for deduction.
3760 QualType P = Context.getCanonicalType(FromType);
3761 QualType A = Context.getCanonicalType(ToType);
3762
Douglas Gregord99609a2011-03-06 09:03:20 +00003763 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003764 // If P is a reference type, the type referred to by P is used for
3765 // type deduction.
3766 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3767 P = PRef->getPointeeType();
3768
Douglas Gregord99609a2011-03-06 09:03:20 +00003769 // C++0x [temp.deduct.conv]p4:
3770 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003771 // for type deduction.
3772 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003773 A = ARef->getPointeeType().getUnqualifiedType();
3774 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003775 //
Mike Stump11289f42009-09-09 15:08:12 +00003776 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003777 else {
3778 assert(!A->isReferenceType() && "Reference types were handled above");
3779
3780 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003781 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003782 // of P for type deduction; otherwise,
3783 if (P->isArrayType())
3784 P = Context.getArrayDecayedType(P);
3785 // - If P is a function type, the pointer type produced by the
3786 // function-to-pointer standard conversion (4.3) is used in
3787 // place of P for type deduction; otherwise,
3788 else if (P->isFunctionType())
3789 P = Context.getPointerType(P);
3790 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003791 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003792 else
3793 P = P.getUnqualifiedType();
3794
Douglas Gregord99609a2011-03-06 09:03:20 +00003795 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003796 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003797 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003798 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003799 A = A.getUnqualifiedType();
3800 }
3801
Eli Friedman77dcc722012-02-08 03:07:05 +00003802 // Unevaluated SFINAE context.
3803 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003804 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003805
3806 // C++ [temp.deduct.conv]p1:
3807 // Template argument deduction is done by comparing the return
3808 // type of the template conversion function (call it P) with the
3809 // type that is required as the result of the conversion (call it
3810 // A) as described in 14.8.2.4.
3811 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003812 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003813 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003814 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003815
3816 // C++0x [temp.deduct.conv]p4:
3817 // In general, the deduction process attempts to find template
3818 // argument values that will make the deduced A identical to
3819 // A. However, there are two cases that allow a difference:
3820 unsigned TDF = 0;
3821 // - If the original A is a reference type, A can be more
3822 // cv-qualified than the deduced A (i.e., the type referred to
3823 // by the reference)
3824 if (ToType->isReferenceType())
3825 TDF |= TDF_ParamWithReferenceType;
3826 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003827 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003828 // conversion.
3829 //
3830 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3831 // both P and A are pointers or member pointers. In this case, we
3832 // just ignore cv-qualifiers completely).
3833 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003834 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003835 TDF |= TDF_IgnoreQualifiers;
3836 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003837 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3838 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003839 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003840
3841 // Create an Instantiation Scope for finalizing the operator.
3842 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003843 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003844 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003845 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003846 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003847 ConversionSpecialized, Info);
3848 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3849
3850 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003851 // to a ptr-to-function, use the deduced arguments from the conversion
3852 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003853 // e.g., int (*fp)(int) = [](auto a) { return a; };
3854 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003855
Faisal Vali2b3a3012013-10-24 23:40:02 +00003856 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003857 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003858 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003859 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003861 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003863 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3864
Simon Pilgrim728134c2016-08-12 11:43:57 +00003865 // Create the corresponding specializations of the call operator and
3866 // the static-invoker; and if the return type is auto,
3867 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003868 // DestFunctionPtrReturnType.
3869 // For instance:
3870 // auto L = [](auto a) { return f(a); };
3871 // int (*fp)(int) = L;
3872 // char (*fp2)(int) = L; <-- Not OK.
3873
3874 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003875 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003876 Info, *this);
3877 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003878 return Result;
3879}
3880
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003881/// \brief Deduce template arguments for a function template when there is
3882/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3883///
3884/// \param FunctionTemplate the function template for which we are performing
3885/// template argument deduction.
3886///
James Dennett18348b62012-06-22 08:52:37 +00003887/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003888/// arguments.
3889///
3890/// \param Specialization if template argument deduction was successful,
3891/// this will be set to the function template specialization produced by
3892/// template argument deduction.
3893///
3894/// \param Info the argument will be updated to provide additional information
3895/// about template argument deduction.
3896///
Richard Smithbaa47832016-12-01 02:11:49 +00003897/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3898/// the address of a function template in a context where we do not have a
3899/// target type, per [over.over]. If \c false, we are looking up a function
3900/// template specialization based on its signature, which only happens when
3901/// deducing a function parameter type from an argument that is a template-id
3902/// naming a function template specialization.
3903///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003904/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003905Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3906 FunctionTemplateDecl *FunctionTemplate,
3907 TemplateArgumentListInfo *ExplicitTemplateArgs,
3908 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3909 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003910 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003911 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003912 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003913}
3914
Richard Smith30482bc2011-02-20 03:19:35 +00003915namespace {
3916 /// Substitute the 'auto' type specifier within a type for a given replacement
3917 /// type.
3918 class SubstituteAutoTransform :
3919 public TreeTransform<SubstituteAutoTransform> {
3920 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003921 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003922 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003923 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3924 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003925 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003926 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003927
Richard Smith30482bc2011-02-20 03:19:35 +00003928 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3929 // If we're building the type pattern to deduce against, don't wrap the
3930 // substituted type in an AutoType. Certain template deduction rules
3931 // apply only when a template type parameter appears directly (and not if
3932 // the parameter is found through desugaring). For instance:
3933 // auto &&lref = lvalue;
3934 // must transform into "rvalue reference to T" not "rvalue reference to
3935 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003936 if (!UseAutoSugar) {
3937 assert(isa<TemplateTypeParmType>(Replacement) &&
3938 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003939 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003940 TemplateTypeParmTypeLoc NewTL =
3941 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003942 NewTL.setNameLoc(TL.getNameLoc());
3943 return Result;
3944 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00003945 QualType Result = SemaRef.Context.getAutoType(
3946 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003947 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3948 NewTL.setNameLoc(TL.getNameLoc());
3949 return Result;
3950 }
3951 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003952
3953 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3954 // Lambdas never need to be transformed.
3955 return E;
3956 }
Richard Smith061f1e22013-04-30 21:23:01 +00003957
Richard Smith2a7d4812013-05-04 07:00:32 +00003958 QualType Apply(TypeLoc TL) {
3959 // Create some scratch storage for the transformed type locations.
3960 // FIXME: We're just going to throw this information away. Don't build it.
3961 TypeLocBuilder TLB;
3962 TLB.reserve(TL.getFullDataSize());
3963 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003964 }
Richard Smith30482bc2011-02-20 03:19:35 +00003965 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003966}
Richard Smith30482bc2011-02-20 03:19:35 +00003967
Richard Smith2a7d4812013-05-04 07:00:32 +00003968Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003969Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
3970 Optional<unsigned> DependentDeductionDepth) {
3971 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
3972 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00003973}
3974
Richard Smith061f1e22013-04-30 21:23:01 +00003975/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003976///
Richard Smith87d263e2016-12-25 08:05:23 +00003977/// Note that this is done even if the initializer is dependent. (This is
3978/// necessary to support partial ordering of templates using 'auto'.)
3979/// A dependent type will be produced when deducing from a dependent type.
3980///
Richard Smith30482bc2011-02-20 03:19:35 +00003981/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003982/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003983/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003984/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00003985/// \param DependentDeductionDepth Set if we should permit deduction in
3986/// dependent cases. This is necessary for template partial ordering with
3987/// 'auto' template parameters. The value specified is the template
3988/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00003989Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003990Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
3991 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00003992 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003993 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3994 if (NonPlaceholder.isInvalid())
3995 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003996 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003997 }
3998
Richard Smith87d263e2016-12-25 08:05:23 +00003999 if (!DependentDeductionDepth &&
4000 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4001 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004002 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004003 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004004 }
4005
Richard Smith87d263e2016-12-25 08:05:23 +00004006 // Find the depth of template parameter to synthesize.
4007 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4008
Richard Smith74aeef52013-04-26 16:15:35 +00004009 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4010 // Since 'decltype(auto)' can only occur at the top of the type, we
4011 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004012 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004013 if (AT->isDecltypeAuto()) {
4014 if (isa<InitListExpr>(Init)) {
4015 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4016 return DAR_FailedAlreadyDiagnosed;
4017 }
4018
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004019 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004020 if (Deduced.isNull())
4021 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004022 // FIXME: Support a non-canonical deduced type for 'auto'.
4023 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004024 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004025 if (Result.isNull())
4026 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004027 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004028 } else if (!getLangOpts().CPlusPlus) {
4029 if (isa<InitListExpr>(Init)) {
4030 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4031 return DAR_FailedAlreadyDiagnosed;
4032 }
Richard Smith74aeef52013-04-26 16:15:35 +00004033 }
4034 }
4035
Richard Smith30482bc2011-02-20 03:19:35 +00004036 SourceLocation Loc = Init->getExprLoc();
4037
4038 LocalInstantiationScope InstScope(*this);
4039
4040 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004041 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4042 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004043 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4044 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004045 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4046 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004047
Richard Smith87d263e2016-12-25 08:05:23 +00004048 QualType FuncParam =
4049 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4050 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004051 assert(!FuncParam.isNull() &&
4052 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004053
4054 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004055 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004056 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004057
Richard Smith87d263e2016-12-25 08:05:23 +00004058 TemplateDeductionInfo Info(Loc, Depth);
4059
4060 // If deduction failed, don't diagnose if the initializer is dependent; it
4061 // might acquire a matching type in the instantiation.
4062 auto DeductionFailed = [&]() -> DeduceAutoResult {
4063 if (Init->isTypeDependent()) {
4064 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4065 assert(!Result.isNull() && "substituting DependentTy can't fail");
4066 return DAR_Succeeded;
4067 }
4068 return DAR_Failed;
4069 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004070
Richard Smith707eab62017-01-05 04:08:31 +00004071 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4072
Richard Smith74801c82012-07-08 04:13:07 +00004073 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004074 if (InitList) {
4075 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004076 if (DeduceTemplateArgumentsFromCallArgument(
4077 *this, TemplateParamsSt.get(), TemplArg, InitList->getInit(i),
4078 Info, Deduced, OriginalCallArgs, None, /*TDF*/0))
Richard Smith87d263e2016-12-25 08:05:23 +00004079 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004080 }
4081 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004082 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4083 Diag(Loc, diag::err_auto_bitfield);
4084 return DAR_FailedAlreadyDiagnosed;
4085 }
4086
Richard Smith707eab62017-01-05 04:08:31 +00004087 if (DeduceTemplateArgumentsFromCallArgument(
4088 *this, TemplateParamsSt.get(), FuncParam, Init, Info, Deduced,
4089 OriginalCallArgs, /*ArgIdx*/0, /*TDF*/0))
Richard Smith87d263e2016-12-25 08:05:23 +00004090 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004091 }
Richard Smith30482bc2011-02-20 03:19:35 +00004092
Richard Smith87d263e2016-12-25 08:05:23 +00004093 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004094 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004095 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004096
Eli Friedmane4310952012-11-06 23:56:42 +00004097 QualType DeducedType = Deduced[0].getAsType();
4098
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004099 if (InitList) {
4100 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4101 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004102 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004103 }
4104
Richard Smith061f1e22013-04-30 21:23:01 +00004105 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004106 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004107 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004108
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004109 // Check that the deduced argument type is compatible with the original
4110 // argument type per C++ [temp.deduct.call]p4.
Richard Smith707eab62017-01-05 04:08:31 +00004111 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4112 if (CheckOriginalCallArgDeduction(*this, OriginalArg, Result)) {
4113 Result = QualType();
4114 return DeductionFailed();
4115 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004116 }
4117
Sebastian Redl09edce02012-01-23 22:09:39 +00004118 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004119}
4120
Simon Pilgrim728134c2016-08-12 11:43:57 +00004121QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004122 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004123 if (TypeToReplaceAuto->isDependentType())
4124 TypeToReplaceAuto = QualType();
4125 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4126 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004127}
4128
Simon Pilgrim728134c2016-08-12 11:43:57 +00004129TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004130 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004131 if (TypeToReplaceAuto->isDependentType())
4132 TypeToReplaceAuto = QualType();
4133 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4134 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004135}
4136
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004137void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4138 if (isa<InitListExpr>(Init))
4139 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004140 VDecl->isInitCapture()
4141 ? diag::err_init_capture_deduction_failure_from_init_list
4142 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004143 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4144 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004145 Diag(VDecl->getLocation(),
4146 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4147 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004148 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4149 << Init->getSourceRange();
4150}
4151
Richard Smith2a7d4812013-05-04 07:00:32 +00004152bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4153 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004154 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004155
4156 if (FD->getTemplateInstantiationPattern())
4157 InstantiateFunctionDefinition(Loc, FD);
4158
Alp Toker314cc812014-01-25 16:55:45 +00004159 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004160 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4161 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4162 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4163 }
4164
4165 return StillUndeduced;
4166}
4167
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004168static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004169MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004170 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004171 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004172 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173
4174/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004175static void
4176AddImplicitObjectParameterType(ASTContext &Context,
4177 CXXMethodDecl *Method,
4178 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004179 // C++11 [temp.func.order]p3:
4180 // [...] The new parameter is of type "reference to cv A," where cv are
4181 // the cv-qualifiers of the function template (if any) and A is
4182 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004183 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004184 // The standard doesn't say explicitly, but we pick the appropriate kind of
4185 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004186 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4187 ArgTy = Context.getQualifiedType(ArgTy,
4188 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004189 if (Method->getRefQualifier() == RQ_RValue)
4190 ArgTy = Context.getRValueReferenceType(ArgTy);
4191 else
4192 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004193 ArgTypes.push_back(ArgTy);
4194}
4195
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004196/// \brief Determine whether the function template \p FT1 is at least as
4197/// specialized as \p FT2.
4198static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004199 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004200 FunctionTemplateDecl *FT1,
4201 FunctionTemplateDecl *FT2,
4202 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004203 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004204 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004206 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4207 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004209 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4210 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004211 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004212 Deduced.resize(TemplateParams->size());
4213
4214 // C++0x [temp.deduct.partial]p3:
4215 // The types used to determine the ordering depend on the context in which
4216 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004217 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004218 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004219 switch (TPOC) {
4220 case TPOC_Call: {
4221 // - In the context of a function call, the function parameter types are
4222 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004223 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4224 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004225
Eli Friedman3b5774a2012-09-19 23:27:04 +00004226 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004227 // [...] If only one of the function templates is a non-static
4228 // member, that function template is considered to have a new
4229 // first parameter inserted in its function parameter list. The
4230 // new parameter is of type "reference to cv A," where cv are
4231 // the cv-qualifiers of the function template (if any) and A is
4232 // the class of which the function template is a member.
4233 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004234 // Note that we interpret this to mean "if one of the function
4235 // templates is a non-static member and the other is a non-member";
4236 // otherwise, the ordering rules for static functions against non-static
4237 // functions don't make any sense.
4238 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004239 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4240 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004241 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004242
Richard Smithe5b52202013-09-11 00:52:39 +00004243 unsigned NumComparedArguments = NumCallArguments1;
4244
4245 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004246 // Compare 'this' from Method1 against first parameter from Method2.
4247 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4248 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004249 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004250 // Compare 'this' from Method2 against first parameter from Method1.
4251 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004252 }
4253
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004254 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004255 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004256 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004257 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregorb837ea42011-01-11 17:34:58 +00004259 // C++ [temp.func.order]p5:
4260 // The presence of unused ellipsis and default arguments has no effect on
4261 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004262 if (Args1.size() > NumComparedArguments)
4263 Args1.resize(NumComparedArguments);
4264 if (Args2.size() > NumComparedArguments)
4265 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004266 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4267 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004268 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004269 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004271 break;
4272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004274 case TPOC_Conversion:
4275 // - In the context of a call to a conversion operator, the return types
4276 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004277 if (DeduceTemplateArgumentsByTypeMatch(
4278 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4279 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004280 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 return false;
4282 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004284 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004285 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004287 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4288 FD2->getType(), FD1->getType(),
4289 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004290 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004291 return false;
4292 break;
4293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004295 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 // In most cases, all template parameters must have values in order for
4297 // deduction to succeed, but for partial ordering purposes a template
4298 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004299 // types being used for partial ordering. [ Note: a template parameter used
4300 // in a non-deduced context is considered used. -end note]
4301 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4302 for (; ArgIdx != NumArgs; ++ArgIdx)
4303 if (Deduced[ArgIdx].isNull())
4304 break;
4305
Richard Smithcf824862016-12-30 04:32:02 +00004306 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4307 // to substitute the deduced arguments back into the template and check that
4308 // we get the right type.
4309
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004310 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004312 // as FT2.
4313 return true;
4314 }
4315
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004316 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004317 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004318 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004319 case TPOC_Call:
4320 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4321 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004322 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004323 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004324 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004326 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004327 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4328 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004329 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004331 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004332 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004333 TemplateParams->getDepth(),
4334 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004335 break;
4336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004338 for (; ArgIdx != NumArgs; ++ArgIdx)
4339 // If this argument had no value deduced but was used in one of the types
4340 // used for partial ordering, then deduction fails.
4341 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4342 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004344 return true;
4345}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregorcef1a032011-01-16 16:03:23 +00004347/// \brief Determine whether this a function template whose parameter-type-list
4348/// ends with a function parameter pack.
4349static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4350 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4351 unsigned NumParams = Function->getNumParams();
4352 if (NumParams == 0)
4353 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354
Douglas Gregorcef1a032011-01-16 16:03:23 +00004355 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4356 if (!Last->isParameterPack())
4357 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Douglas Gregorcef1a032011-01-16 16:03:23 +00004359 // Make sure that no previous parameter is a parameter pack.
4360 while (--NumParams > 0) {
4361 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4362 return false;
4363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
Douglas Gregorcef1a032011-01-16 16:03:23 +00004365 return true;
4366}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregorbe999392009-09-15 16:23:51 +00004368/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004369/// to the rules of function template partial ordering (C++ [temp.func.order]).
4370///
4371/// \param FT1 the first function template
4372///
4373/// \param FT2 the second function template
4374///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004375/// \param TPOC the context in which we are performing partial ordering of
4376/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004377///
Richard Smithe5b52202013-09-11 00:52:39 +00004378/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4379/// only when \c TPOC is \c TPOC_Call.
4380///
4381/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4382/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004383///
Douglas Gregorbe999392009-09-15 16:23:51 +00004384/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004385/// template is more specialized, returns NULL.
4386FunctionTemplateDecl *
4387Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4388 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004389 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004390 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004391 unsigned NumCallArguments1,
4392 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004394 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004396 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004398 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004399 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004401 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004402 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004403
Douglas Gregorcef1a032011-01-16 16:03:23 +00004404 // FIXME: This mimics what GCC implements, but doesn't match up with the
4405 // proposed resolution for core issue 692. This area needs to be sorted out,
4406 // but for now we attempt to maintain compatibility.
4407 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4408 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4409 if (Variadic1 != Variadic2)
4410 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Craig Topperc3ec1492014-05-26 06:22:03 +00004412 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004413}
Douglas Gregor9b146582009-07-08 20:55:45 +00004414
Douglas Gregor450f00842009-09-25 18:43:00 +00004415/// \brief Determine if the two templates are equivalent.
4416static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4417 if (T1 == T2)
4418 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Douglas Gregor450f00842009-09-25 18:43:00 +00004420 if (!T1 || !T2)
4421 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregor450f00842009-09-25 18:43:00 +00004423 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4424}
4425
4426/// \brief Retrieve the most specialized of the given function template
4427/// specializations.
4428///
John McCall58cc69d2010-01-27 01:50:18 +00004429/// \param SpecBegin the start iterator of the function template
4430/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004431///
John McCall58cc69d2010-01-27 01:50:18 +00004432/// \param SpecEnd the end iterator of the function template
4433/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004434///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004436/// diagnostic should occur.
4437///
4438/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4439/// no matching candidates.
4440///
4441/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4442/// occurs.
4443///
4444/// \param CandidateDiag partial diagnostic used for each function template
4445/// specialization that is a candidate in the ambiguous ordering. One parameter
4446/// in this diagnostic should be unbound, which will correspond to the string
4447/// describing the template arguments for the function template specialization.
4448///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004450/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004451UnresolvedSetIterator Sema::getMostSpecialized(
4452 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4453 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004454 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4455 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4456 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004457 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004458 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004459 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004460 FailedCandidates.NoteCandidates(*this, Loc);
4461 }
John McCall58cc69d2010-01-27 01:50:18 +00004462 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
4465 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004466 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 // Find the function template that is better than all of the templates it
4469 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004470 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004472 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004473 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004474 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4475 FunctionTemplateDecl *Challenger
4476 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004477 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004478 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004479 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004480 Challenger)) {
4481 Best = I;
4482 BestTemplate = Challenger;
4483 }
4484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregor450f00842009-09-25 18:43:00 +00004486 // Make sure that the "best" function template is more specialized than all
4487 // of the others.
4488 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004489 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4490 FunctionTemplateDecl *Challenger
4491 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004492 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004494 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 BestTemplate)) {
4496 Ambiguous = true;
4497 break;
4498 }
4499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500
Douglas Gregor450f00842009-09-25 18:43:00 +00004501 if (!Ambiguous) {
4502 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004503 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
Douglas Gregor450f00842009-09-25 18:43:00 +00004506 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004507 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004508 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Richard Smithb875c432013-05-04 01:51:08 +00004510 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004511 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4512 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004513 const auto *FD = cast<FunctionDecl>(*I);
4514 PD << FD << getTemplateArgumentBindingsText(
4515 FD->getPrimaryTemplate()->getTemplateParameters(),
4516 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004517 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004518 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004519 Diag((*I)->getLocation(), PD);
4520 }
Richard Smithb875c432013-05-04 01:51:08 +00004521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
John McCall58cc69d2010-01-27 01:50:18 +00004523 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004524}
4525
Richard Smith0da6dc42016-12-24 16:40:51 +00004526/// Determine whether one partial specialization, P1, is at least as
4527/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004528///
Richard Smith26b86ea2016-12-31 21:41:23 +00004529/// \tparam TemplateLikeDecl The kind of P2, which must be a
4530/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004531/// \param T1 The injected-class-name of P1 (faked for a variable template).
4532/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004533template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004534static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004535 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004536 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004537 // C++ [temp.class.order]p1:
4538 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 // specialized as the second if, given the following rewrite to two
4540 // function templates, the first function template is at least as
4541 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004542 // templates (14.6.6.2):
4543 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544 // first partial specialization and has a single function parameter
4545 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004546 // arguments of the first partial specialization, and
4547 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 // second partial specialization and has a single function parameter
4549 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004550 // arguments of the second partial specialization.
4551 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004552 // Rather than synthesize function templates, we merely perform the
4553 // equivalent partial ordering by performing deduction directly on
4554 // the template arguments of the class template partial
4555 // specializations. This computation is slightly simpler than the
4556 // general problem of function template partial ordering, because
4557 // class template partial specializations are more constrained. We
4558 // know that every template parameter is deducible from the class
4559 // template partial specialization's template arguments, for
4560 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004561 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004562
Richard Smith0da6dc42016-12-24 16:40:51 +00004563 // Determine whether P1 is at least as specialized as P2.
4564 Deduced.resize(P2->getTemplateParameters()->size());
4565 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4566 T2, T1, Info, Deduced, TDF_None,
4567 /*PartialOrdering=*/true))
4568 return false;
4569
4570 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4571 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004572 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4573 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004574 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4575 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004576 S, P2, /*PartialOrdering=*/true,
4577 TemplateArgumentList(TemplateArgumentList::OnStack,
4578 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004579 Deduced, Info))
4580 return false;
4581
4582 return true;
4583}
4584
4585/// \brief Returns the more specialized class template partial specialization
4586/// according to the rules of partial ordering of class template partial
4587/// specializations (C++ [temp.class.order]).
4588///
4589/// \param PS1 the first class template partial specialization
4590///
4591/// \param PS2 the second class template partial specialization
4592///
4593/// \returns the more specialized class template partial specialization. If
4594/// neither partial specialization is more specialized, returns NULL.
4595ClassTemplatePartialSpecializationDecl *
4596Sema::getMoreSpecializedPartialSpecialization(
4597 ClassTemplatePartialSpecializationDecl *PS1,
4598 ClassTemplatePartialSpecializationDecl *PS2,
4599 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004600 QualType PT1 = PS1->getInjectedSpecializationType();
4601 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
Richard Smith0e617ec2016-12-27 07:56:27 +00004603 TemplateDeductionInfo Info(Loc);
4604 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4605 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004606
4607 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004608 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004609
4610 return Better1 ? PS1 : PS2;
4611}
4612
Richard Smith0e617ec2016-12-27 07:56:27 +00004613bool Sema::isMoreSpecializedThanPrimary(
4614 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4615 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4616 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4617 QualType PartialT = Spec->getInjectedSpecializationType();
4618 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4619 return false;
4620 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4621 Info.clearSFINAEDiagnostic();
4622 return false;
4623 }
4624 return true;
4625}
4626
Larisse Voufo39a1e502013-08-06 01:03:05 +00004627VarTemplatePartialSpecializationDecl *
4628Sema::getMoreSpecializedPartialSpecialization(
4629 VarTemplatePartialSpecializationDecl *PS1,
4630 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004631 // Pretend the variable template specializations are class template
4632 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004633 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004634 "the partial specializations being compared should specialize"
4635 " the same template.");
4636 TemplateName Name(PS1->getSpecializedTemplate());
4637 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4638 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004639 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004640 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004641 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004642
Richard Smith0e617ec2016-12-27 07:56:27 +00004643 TemplateDeductionInfo Info(Loc);
4644 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4645 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
Douglas Gregorbe999392009-09-15 16:23:51 +00004647 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004648 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Richard Smith0da6dc42016-12-24 16:40:51 +00004650 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004651}
4652
Richard Smith0e617ec2016-12-27 07:56:27 +00004653bool Sema::isMoreSpecializedThanPrimary(
4654 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4655 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4656 // FIXME: Cache the injected template arguments rather than recomputing
4657 // them for each partial specialization.
4658 SmallVector<TemplateArgument, 8> PrimaryArgs;
4659 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4660 PrimaryArgs);
4661
4662 TemplateName CanonTemplate =
4663 Context.getCanonicalTemplateName(TemplateName(Primary));
4664 QualType PrimaryT = Context.getTemplateSpecializationType(
4665 CanonTemplate, PrimaryArgs);
4666 QualType PartialT = Context.getTemplateSpecializationType(
4667 CanonTemplate, Spec->getTemplateArgs().asArray());
4668 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4669 return false;
4670 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4671 Info.clearSFINAEDiagnostic();
4672 return false;
4673 }
4674 return true;
4675}
4676
Richard Smith26b86ea2016-12-31 21:41:23 +00004677bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4678 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4679 // C++1z [temp.arg.template]p4: (DR 150)
4680 // A template template-parameter P is at least as specialized as a
4681 // template template-argument A if, given the following rewrite to two
4682 // function templates...
4683
4684 // Rather than synthesize function templates, we merely perform the
4685 // equivalent partial ordering by performing deduction directly on
4686 // the template parameter lists of the template template parameters.
4687 //
4688 // Given an invented class template X with the template parameter list of
4689 // A (including default arguments):
4690 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4691 TemplateParameterList *A = AArg->getTemplateParameters();
4692
4693 // - Each function template has a single function parameter whose type is
4694 // a specialization of X with template arguments corresponding to the
4695 // template parameters from the respective function template
4696 SmallVector<TemplateArgument, 8> AArgs;
4697 Context.getInjectedTemplateArgs(A, AArgs);
4698
4699 // Check P's arguments against A's parameter list. This will fill in default
4700 // template arguments as needed. AArgs are already correct by construction.
4701 // We can't just use CheckTemplateIdType because that will expand alias
4702 // templates.
4703 SmallVector<TemplateArgument, 4> PArgs;
4704 {
4705 SFINAETrap Trap(*this);
4706
4707 Context.getInjectedTemplateArgs(P, PArgs);
4708 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4709 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4710 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4711 // expansions, to form an "as written" argument list.
4712 TemplateArgument Arg = PArgs[I];
4713 if (Arg.getKind() == TemplateArgument::Pack) {
4714 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4715 Arg = *Arg.pack_begin();
4716 }
4717 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4718 Arg, QualType(), P->getParam(I)->getLocation()));
4719 }
4720 PArgs.clear();
4721
4722 // C++1z [temp.arg.template]p3:
4723 // If the rewrite produces an invalid type, then P is not at least as
4724 // specialized as A.
4725 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4726 Trap.hasErrorOccurred())
4727 return false;
4728 }
4729
4730 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4731 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4732
Richard Smith26b86ea2016-12-31 21:41:23 +00004733 // ... the function template corresponding to P is at least as specialized
4734 // as the function template corresponding to A according to the partial
4735 // ordering rules for function templates.
4736 TemplateDeductionInfo Info(Loc, A->getDepth());
4737 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4738}
4739
Mike Stump11289f42009-09-09 15:08:12 +00004740static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004741MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004742 const TemplateArgument &TemplateArg,
4743 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004744 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004745 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004746
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004747/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004748/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004749static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004750MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004751 const Expr *E,
4752 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004753 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004754 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004755 // We can deduce from a pack expansion.
4756 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4757 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Richard Smith34349002012-07-09 03:07:20 +00004759 // Skip through any implicit casts we added while type-checking, and any
4760 // substitutions performed by template alias expansion.
4761 while (1) {
4762 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4763 E = ICE->getSubExpr();
4764 else if (const SubstNonTypeTemplateParmExpr *Subst =
4765 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4766 E = Subst->getReplacement();
4767 else
4768 break;
4769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
4771 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004772 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004773 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004774 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004775 return;
4776
Mike Stump11289f42009-09-09 15:08:12 +00004777 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004778 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4779 if (!NTTP)
4780 return;
4781
Douglas Gregor21610382009-10-29 00:04:11 +00004782 if (NTTP->getDepth() == Depth)
4783 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004784
4785 // In C++1z mode, additional arguments may be deduced from the type of a
4786 // non-type argument.
4787 if (Ctx.getLangOpts().CPlusPlus1z)
4788 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004789}
4790
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004791/// \brief Mark the template parameters that are used by the given
4792/// nested name specifier.
4793static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004794MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004795 NestedNameSpecifier *NNS,
4796 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004797 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004798 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004799 if (!NNS)
4800 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004802 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004803 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004804 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004805 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004807
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004808/// \brief Mark the template parameters that are used by the given
4809/// template name.
4810static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004811MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004812 TemplateName Name,
4813 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004814 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004815 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004816 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4817 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004818 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4819 if (TTP->getDepth() == Depth)
4820 Used[TTP->getIndex()] = true;
4821 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004822 return;
4823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004825 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004826 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004827 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004828 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004829 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004830 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004831}
4832
4833/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004834/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004835static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004836MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004837 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004838 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004839 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004840 if (T.isNull())
4841 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004842
Douglas Gregor91772d12009-06-13 00:26:55 +00004843 // Non-dependent types have nothing deducible
4844 if (!T->isDependentType())
4845 return;
4846
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004847 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004848 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004849 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004850 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004851 cast<PointerType>(T)->getPointeeType(),
4852 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004853 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004854 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004855 break;
4856
4857 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004858 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004859 cast<BlockPointerType>(T)->getPointeeType(),
4860 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004861 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004862 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004863 break;
4864
4865 case Type::LValueReference:
4866 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004867 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004868 cast<ReferenceType>(T)->getPointeeType(),
4869 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004870 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004872 break;
4873
4874 case Type::MemberPointer: {
4875 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004876 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004877 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004878 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004879 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004880 break;
4881 }
4882
4883 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004884 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004885 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004886 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004887 // Fall through to check the element type
4888
4889 case Type::ConstantArray:
4890 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004891 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004892 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004893 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004894 break;
4895
4896 case Type::Vector:
4897 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004898 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004899 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004900 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004901 break;
4902
Douglas Gregor758a8692009-06-17 21:51:59 +00004903 case Type::DependentSizedExtVector: {
4904 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004905 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004906 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004907 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004908 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004909 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004910 break;
4911 }
4912
Douglas Gregor91772d12009-06-13 00:26:55 +00004913 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004914 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004915 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4916 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004917 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4918 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004919 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004920 break;
4921 }
4922
Douglas Gregor21610382009-10-29 00:04:11 +00004923 case Type::TemplateTypeParm: {
4924 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4925 if (TTP->getDepth() == Depth)
4926 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004927 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004928 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004929
Douglas Gregorfb322d82011-01-14 05:11:40 +00004930 case Type::SubstTemplateTypeParmPack: {
4931 const SubstTemplateTypeParmPackType *Subst
4932 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004933 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004934 QualType(Subst->getReplacedParameter(), 0),
4935 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004936 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004937 OnlyDeduced, Depth, Used);
4938 break;
4939 }
4940
John McCall2408e322010-04-27 00:57:59 +00004941 case Type::InjectedClassName:
4942 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4943 // fall through
4944
Douglas Gregor91772d12009-06-13 00:26:55 +00004945 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004946 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004947 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004948 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004949 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004950
Douglas Gregord0ad2942010-12-23 01:24:45 +00004951 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004952 // If the template argument list of P contains a pack expansion that is
4953 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004954 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004956 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004957 break;
4958
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004959 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004960 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004961 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004962 break;
4963 }
4964
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004965 case Type::Complex:
4966 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004967 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004968 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004969 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004970 break;
4971
Eli Friedman0dfb8892011-10-06 23:00:33 +00004972 case Type::Atomic:
4973 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004974 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004975 cast<AtomicType>(T)->getValueType(),
4976 OnlyDeduced, Depth, Used);
4977 break;
4978
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004979 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004980 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004981 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004982 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004983 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004984 break;
4985
John McCallc392f372010-06-11 00:33:02 +00004986 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004987 // C++14 [temp.deduct.type]p5:
4988 // The non-deduced contexts are:
4989 // -- The nested-name-specifier of a type that was specified using a
4990 // qualified-id
4991 //
4992 // C++14 [temp.deduct.type]p6:
4993 // When a type name is specified in a way that includes a non-deduced
4994 // context, all of the types that comprise that type name are also
4995 // non-deduced.
4996 if (OnlyDeduced)
4997 break;
4998
John McCallc392f372010-06-11 00:33:02 +00004999 const DependentTemplateSpecializationType *Spec
5000 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Richard Smith50d5b972015-12-30 20:56:05 +00005002 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5003 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005004
John McCallc392f372010-06-11 00:33:02 +00005005 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005006 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005007 Used);
5008 break;
5009 }
5010
John McCallbd8d9bd2010-03-01 23:49:17 +00005011 case Type::TypeOf:
5012 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005013 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005014 cast<TypeOfType>(T)->getUnderlyingType(),
5015 OnlyDeduced, Depth, Used);
5016 break;
5017
5018 case Type::TypeOfExpr:
5019 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005020 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005021 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5022 OnlyDeduced, Depth, Used);
5023 break;
5024
5025 case Type::Decltype:
5026 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005027 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005028 cast<DecltypeType>(T)->getUnderlyingExpr(),
5029 OnlyDeduced, Depth, Used);
5030 break;
5031
Alexis Hunte852b102011-05-24 22:41:36 +00005032 case Type::UnaryTransform:
5033 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005034 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005035 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005036 OnlyDeduced, Depth, Used);
5037 break;
5038
Douglas Gregord2fa7662010-12-20 02:24:11 +00005039 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005040 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005041 cast<PackExpansionType>(T)->getPattern(),
5042 OnlyDeduced, Depth, Used);
5043 break;
5044
Richard Smith30482bc2011-02-20 03:19:35 +00005045 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005046 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005047 cast<AutoType>(T)->getDeducedType(),
5048 OnlyDeduced, Depth, Used);
5049
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005050 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005051 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005052 case Type::VariableArray:
5053 case Type::FunctionNoProto:
5054 case Type::Record:
5055 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005056 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005057 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005058 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005059 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005060 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005061#define TYPE(Class, Base)
5062#define ABSTRACT_TYPE(Class, Base)
5063#define DEPENDENT_TYPE(Class, Base)
5064#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5065#include "clang/AST/TypeNodes.def"
5066 break;
5067 }
5068}
5069
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005070/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005071/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005072static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005073MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005074 const TemplateArgument &TemplateArg,
5075 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005076 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005077 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005078 switch (TemplateArg.getKind()) {
5079 case TemplateArgument::Null:
5080 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005081 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005082 break;
Mike Stump11289f42009-09-09 15:08:12 +00005083
Eli Friedmanb826a002012-09-26 02:36:12 +00005084 case TemplateArgument::NullPtr:
5085 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5086 Depth, Used);
5087 break;
5088
Douglas Gregor91772d12009-06-13 00:26:55 +00005089 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005090 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005091 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005092 break;
5093
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005094 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005095 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005096 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005098 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005099 break;
5100
5101 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005102 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005103 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Anders Carlssonbc343912009-06-15 17:04:53 +00005106 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005107 for (const auto &P : TemplateArg.pack_elements())
5108 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005109 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005110 }
5111}
5112
James Dennett41725122012-06-22 10:16:05 +00005113/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005114/// template argument list.
5115///
5116/// \param TemplateArgs the template argument list from which template
5117/// parameters will be deduced.
5118///
James Dennett41725122012-06-22 10:16:05 +00005119/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005120/// to indicate when the corresponding template parameter will be
5121/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005122void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005123Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005124 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005125 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005126 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127 // If the template argument list of P contains a pack expansion that is not
5128 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005129 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005131 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005132 return;
5133
Douglas Gregor91772d12009-06-13 00:26:55 +00005134 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005135 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005136 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005137}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005138
5139/// \brief Marks all of the template parameters that will be deduced by a
5140/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005141void Sema::MarkDeducedTemplateParameters(
5142 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5143 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005145 = FunctionTemplate->getTemplateParameters();
5146 Deduced.clear();
5147 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005148
Douglas Gregorce23bae2009-09-18 23:21:38 +00005149 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5150 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005151 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005152 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005153}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005154
5155bool hasDeducibleTemplateParameters(Sema &S,
5156 FunctionTemplateDecl *FunctionTemplate,
5157 QualType T) {
5158 if (!T->isDependentType())
5159 return false;
5160
5161 TemplateParameterList *TemplateParams
5162 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005163 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005164 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005165 Deduced);
5166
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005167 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005168}