blob: 043e5c37160f0044d57d41b7061cfded8fe44e61 [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
Richard Smithc92d2062017-01-05 23:02:44 +000022#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000026#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000027#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000028
29namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000030 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000031 /// \brief Various flags that control template argument deduction.
32 ///
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
38 TDF_None = 0,
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
41 /// a reference.
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000048 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000049 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
52 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000053 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000055 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000056 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
59 /// terms of noreturn and default calling convention adjustments.
60 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000061 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000062}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000063
Douglas Gregor55ca8f62009-06-04 00:03:07 +000064using namespace clang;
65
Douglas Gregor0a29a052010-03-26 05:50:28 +000066/// \brief Compare two APSInts, extending and switching the sign as
67/// necessary to compare their values regardless of underlying type.
68static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
69 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000070 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000071 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000072 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000073
74 // If there is a signedness mismatch, correct it.
75 if (X.isSigned() != Y.isSigned()) {
76 // If the signed value is negative, then the values cannot be the same.
77 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
78 return false;
79
80 Y.setIsSigned(true);
81 X.setIsSigned(true);
82 }
83
84 return X == Y;
85}
86
Douglas Gregor181aa4a2009-06-12 18:26:56 +000087static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000088DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000089 TemplateParameterList *TemplateParams,
90 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000091 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000092 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000093 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000094
Douglas Gregor7baabef2010-12-22 18:17:10 +000095static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000096DeduceTemplateArgumentsByTypeMatch(Sema &S,
97 TemplateParameterList *TemplateParams,
98 QualType Param,
99 QualType Arg,
100 TemplateDeductionInfo &Info,
101 SmallVectorImpl<DeducedTemplateArgument> &
102 Deduced,
103 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000104 bool PartialOrdering = false,
105 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000106
107static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000108DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000109 ArrayRef<TemplateArgument> Params,
110 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000111 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000112 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
113 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000114
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000115/// \brief If the given expression is of a form that permits the deduction
116/// of a non-type template parameter, return the declaration of that
117/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000118static NonTypeTemplateParmDecl *
119getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000120 // If we are within an alias template, the expression may have undergone
121 // any number of parameter substitutions already.
122 while (1) {
123 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
124 E = IC->getSubExpr();
125 else if (SubstNonTypeTemplateParmExpr *Subst =
126 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
127 E = Subst->getReplacement();
128 else
129 break;
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000132 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000133 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
134 if (NTTP->getDepth() == Info.getDeducedDepth())
135 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Craig Topperc3ec1492014-05-26 06:22:03 +0000137 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000138}
139
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000140/// \brief Determine whether two declaration pointers refer to the same
141/// declaration.
142static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000143 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
144 X = NX->getUnderlyingDecl();
145 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
146 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000148 return X->getCanonicalDecl() == Y->getCanonicalDecl();
149}
150
151/// \brief Verify that the given, deduced template arguments are compatible.
152///
153/// \returns The deduced template argument, or a NULL template argument if
154/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000156checkDeducedTemplateArguments(ASTContext &Context,
157 const DeducedTemplateArgument &X,
158 const DeducedTemplateArgument &Y) {
159 // We have no deduction for one or both of the arguments; they're compatible.
160 if (X.isNull())
161 return Y;
162 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000163 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000164
Richard Smith593d6a12016-12-23 01:30:39 +0000165 // If we have two non-type template argument values deduced for the same
166 // parameter, they must both match the type of the parameter, and thus must
167 // match each other's type. As we're only keeping one of them, we must check
168 // for that now. The exception is that if either was deduced from an array
169 // bound, the type is permitted to differ.
170 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
171 QualType XType = X.getNonTypeTemplateArgumentType();
172 if (!XType.isNull()) {
173 QualType YType = Y.getNonTypeTemplateArgumentType();
174 if (YType.isNull() || !Context.hasSameType(XType, YType))
175 return DeducedTemplateArgument();
176 }
177 }
178
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000179 switch (X.getKind()) {
180 case TemplateArgument::Null:
181 llvm_unreachable("Non-deduced template arguments handled above");
182
183 case TemplateArgument::Type:
184 // If two template type arguments have the same type, they're compatible.
185 if (Y.getKind() == TemplateArgument::Type &&
186 Context.hasSameType(X.getAsType(), Y.getAsType()))
187 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
Richard Smith5f274382016-09-28 23:55:27 +0000189 // If one of the two arguments was deduced from an array bound, the other
190 // supersedes it.
191 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
192 return X.wasDeducedFromArrayBound() ? Y : X;
193
194 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000195 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000196
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000197 case TemplateArgument::Integral:
198 // If we deduced a constant in one case and either a dependent expression or
199 // declaration in another case, keep the integral constant.
200 // If both are integral constants with the same value, keep that value.
201 if (Y.getKind() == TemplateArgument::Expression ||
202 Y.getKind() == TemplateArgument::Declaration ||
203 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000204 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000205 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206
207 // All other combinations are incompatible.
208 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000210 case TemplateArgument::Template:
211 if (Y.getKind() == TemplateArgument::Template &&
212 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
213 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000214
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000215 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000216 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000217
218 case TemplateArgument::TemplateExpansion:
219 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000220 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000221 Y.getAsTemplateOrTemplatePattern()))
222 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000224 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000226
Richard Smith593d6a12016-12-23 01:30:39 +0000227 case TemplateArgument::Expression: {
228 if (Y.getKind() != TemplateArgument::Expression)
229 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Richard Smith593d6a12016-12-23 01:30:39 +0000231 // Compare the expressions for equality
232 llvm::FoldingSetNodeID ID1, ID2;
233 X.getAsExpr()->Profile(ID1, Context, true);
234 Y.getAsExpr()->Profile(ID2, Context, true);
235 if (ID1 == ID2)
236 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Richard Smith593d6a12016-12-23 01:30:39 +0000238 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000239 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000241
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000242 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000243 assert(!X.wasDeducedFromArrayBound());
244
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000245 // If we deduced a declaration and a dependent expression, keep the
246 // declaration.
247 if (Y.getKind() == TemplateArgument::Expression)
248 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000249
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000250 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000251 // integral constant and whichever type did not come from an array
252 // bound.
253 if (Y.getKind() == TemplateArgument::Integral) {
254 if (Y.wasDeducedFromArrayBound())
255 return TemplateArgument(Context, Y.getAsIntegral(),
256 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000257 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000260 // If we deduced two declarations, make sure they they refer to the
261 // same declaration.
262 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000263 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000264 return X;
265
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
268
269 case TemplateArgument::NullPtr:
270 // If we deduced a null pointer and a dependent expression, keep the
271 // null pointer.
272 if (Y.getKind() == TemplateArgument::Expression)
273 return X;
274
275 // If we deduced a null pointer and an integral constant, keep the
276 // integral constant.
277 if (Y.getKind() == TemplateArgument::Integral)
278 return Y;
279
Richard Smith593d6a12016-12-23 01:30:39 +0000280 // If we deduced two null pointers, they are the same.
281 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000282 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000284 // All other combinations are incompatible.
285 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000287 case TemplateArgument::Pack:
288 if (Y.getKind() != TemplateArgument::Pack ||
289 X.pack_size() != Y.pack_size())
290 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000291
Richard Smith539e8e32017-01-04 01:48:55 +0000292 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000294 XAEnd = X.pack_end(),
295 YA = Y.pack_begin();
296 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000297 TemplateArgument Merged = checkDeducedTemplateArguments(
298 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
299 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
300 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000301 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000302 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
Richard Smith539e8e32017-01-04 01:48:55 +0000305 return DeducedTemplateArgument(
306 TemplateArgument::CreatePackCopy(Context, NewPack),
307 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
David Blaikiee4d798f2012-01-20 21:50:17 +0000310 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311}
312
Mike Stump11289f42009-09-09 15:08:12 +0000313/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000314/// as the given deduced template argument. All non-type template parameter
315/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000316static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000317 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000318 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
319 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000320 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000321 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
322 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000323
Richard Smith5d102892016-12-27 03:59:58 +0000324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
325 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000326 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000327 Info.Param = NTTP;
328 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000334 if (!S.getLangOpts().CPlusPlus1z)
335 return Sema::TDK_Success;
336
337 // FIXME: It's not clear how deduction of a parameter of reference
338 // type from an argument (of non-reference type) should be performed.
339 // For now, we just remove reference types from both sides and let
340 // the final check for matching types sort out the mess.
341 return DeduceTemplateArgumentsByTypeMatch(
342 S, TemplateParams, NTTP->getType().getNonReferenceType(),
343 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
344 /*PartialOrdering=*/false,
345 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000346}
347
Mike Stump11289f42009-09-09 15:08:12 +0000348/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000349/// from the given integral constant.
350static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
351 Sema &S, TemplateParameterList *TemplateParams,
352 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
353 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
354 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
355 return DeduceNonTypeTemplateArgument(
356 S, TemplateParams, NTTP,
357 DeducedTemplateArgument(S.Context, Value, ValueType,
358 DeducedFromArrayBound),
359 ValueType, Info, Deduced);
360}
361
362/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000363/// from the given null pointer template argument type.
364static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000365 Sema &S, TemplateParameterList *TemplateParams,
366 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000367 TemplateDeductionInfo &Info,
368 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
369 Expr *Value =
370 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
371 S.Context.NullPtrTy, NTTP->getLocation()),
372 NullPtrType, CK_NullToPointer)
373 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000374 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
375 DeducedTemplateArgument(Value),
376 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000377}
378
379/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000380/// from the given type- or value-dependent expression.
381///
382/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000383static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
384 Sema &S, TemplateParameterList *TemplateParams,
385 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
386 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000387 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
388 DeducedTemplateArgument(Value),
389 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000390}
391
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000392/// \brief Deduce the value of the given non-type template parameter
393/// from the given declaration.
394///
395/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000396static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
397 Sema &S, TemplateParameterList *TemplateParams,
398 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
399 TemplateDeductionInfo &Info,
400 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000401 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000402 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000403 return DeduceNonTypeTemplateArgument(
404 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000405}
406
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000407static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000408DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000409 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000410 TemplateName Param,
411 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000412 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000413 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000414 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000415 if (!ParamDecl) {
416 // The parameter type is dependent and is not a template template parameter,
417 // so there is nothing that we can deduce.
418 return Sema::TDK_Success;
419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregoradee3e32009-11-11 23:06:43 +0000421 if (TemplateTemplateParmDecl *TempParam
422 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000423 // If we're not deducing at this depth, there's nothing to deduce.
424 if (TempParam->getDepth() != Info.getDeducedDepth())
425 return Sema::TDK_Success;
426
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000427 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000429 Deduced[TempParam->getIndex()],
430 NewDeduced);
431 if (Result.isNull()) {
432 Info.Param = TempParam;
433 Info.FirstArg = Deduced[TempParam->getIndex()];
434 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000438 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000443 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000444 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregoradee3e32009-11-11 23:06:43 +0000446 // Mismatch of non-dependent template parameter to argument.
447 Info.FirstArg = TemplateArgument(Param);
448 Info.SecondArg = TemplateArgument(Arg);
449 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000450}
451
Mike Stump11289f42009-09-09 15:08:12 +0000452/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000453/// type (which is a template-id) with the template argument type.
454///
Chandler Carruthc1263112010-02-07 21:33:28 +0000455/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000456///
457/// \param TemplateParams the template parameters that we are deducing
458///
459/// \param Param the parameter type
460///
461/// \param Arg the argument type
462///
463/// \param Info information about the template argument deduction itself
464///
465/// \param Deduced the deduced template arguments
466///
467/// \returns the result of template argument deduction so far. Note that a
468/// "success" result means that template argument deduction has not yet failed,
469/// but it may still fail, later, for other reasons.
470static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000471DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 TemplateParameterList *TemplateParams,
473 const TemplateSpecializationType *Param,
474 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000475 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000476 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000477 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000478
Douglas Gregore81f3e72009-07-07 23:09:34 +0000479 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000480 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000481 = dyn_cast<TemplateSpecializationType>(Arg)) {
482 // Perform template argument deduction for the template name.
483 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000484 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000485 Param->getTemplateName(),
486 SpecArg->getTemplateName(),
487 Info, Deduced))
488 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregore81f3e72009-07-07 23:09:34 +0000491 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000492 // argument. Ignore any missing/extra arguments, since they could be
493 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000494 return DeduceTemplateArguments(S, TemplateParams,
495 Param->template_arguments(),
496 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000497 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregore81f3e72009-07-07 23:09:34 +0000500 // If the argument type is a class template specialization, we
501 // perform template argument deduction using its template
502 // arguments.
503 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 if (!RecordArg) {
505 Info.FirstArg = TemplateArgument(QualType(Param, 0));
506 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
510 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000511 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000512 if (!SpecArg) {
513 Info.FirstArg = TemplateArgument(QualType(Param, 0));
514 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000515 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregore81f3e72009-07-07 23:09:34 +0000518 // Perform template argument deduction for the template name.
519 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000520 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000521 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000522 Param->getTemplateName(),
523 TemplateName(SpecArg->getSpecializedTemplate()),
524 Info, Deduced))
525 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Douglas Gregor7baabef2010-12-22 18:17:10 +0000527 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000528 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
529 SpecArg->getTemplateArgs().asArray(), Info,
530 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000531}
532
John McCall08569062010-08-28 22:14:41 +0000533/// \brief Determines whether the given type is an opaque type that
534/// might be more qualified when instantiated.
535static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
536 switch (T->getTypeClass()) {
537 case Type::TypeOfExpr:
538 case Type::TypeOf:
539 case Type::DependentName:
540 case Type::Decltype:
541 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000542 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000543 return true;
544
545 case Type::ConstantArray:
546 case Type::IncompleteArray:
547 case Type::VariableArray:
548 case Type::DependentSizedArray:
549 return IsPossiblyOpaquelyQualifiedType(
550 cast<ArrayType>(T)->getElementType());
551
552 default:
553 return false;
554 }
555}
556
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000557/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000559getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
561 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor5499af42011-01-05 23:12:31 +0000563 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
564 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor5499af42011-01-05 23:12:31 +0000566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
567 return std::make_pair(TTP->getDepth(), TTP->getIndex());
568}
569
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000572getDepthAndIndex(UnexpandedParameterPack UPP) {
573 if (const TemplateTypeParmType *TTP
574 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
575 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000577 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
578}
579
Douglas Gregor5499af42011-01-05 23:12:31 +0000580/// \brief Helper function to build a TemplateParameter when we don't
581/// know its type statically.
582static TemplateParameter makeTemplateParameter(Decl *D) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
584 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000585 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000586 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor5499af42011-01-05 23:12:31 +0000588 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
589}
590
Richard Smith0a80d572014-05-29 01:12:14 +0000591/// A pack that we're currently deducing.
592struct clang::DeducedPack {
593 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000594
Richard Smith0a80d572014-05-29 01:12:14 +0000595 // The index of the pack.
596 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Richard Smith0a80d572014-05-29 01:12:14 +0000598 // The old value of the pack before we started deducing it.
599 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000600
Richard Smith0a80d572014-05-29 01:12:14 +0000601 // A deferred value of this pack from an inner deduction, that couldn't be
602 // deduced because this deduction hadn't happened yet.
603 DeducedTemplateArgument DeferredDeduction;
604
605 // The new value of the pack.
606 SmallVector<DeducedTemplateArgument, 4> New;
607
608 // The outer deduction for this pack, if any.
609 DeducedPack *Outer;
610};
611
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000612namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000613/// A scope in which we're performing pack deduction.
614class PackDeductionScope {
615public:
616 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
617 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
618 TemplateDeductionInfo &Info, TemplateArgument Pattern)
619 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
620 // Compute the set of template parameter indices that correspond to
621 // parameter packs expanded by the pack expansion.
622 {
623 llvm::SmallBitVector SawIndices(TemplateParams->size());
624 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
625 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
626 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
627 unsigned Depth, Index;
628 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000629 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000630 SawIndices[Index] = true;
631
632 // Save the deduced template argument for the parameter pack expanded
633 // by this pack expansion, then clear out the deduction.
634 DeducedPack Pack(Index);
635 Pack.Saved = Deduced[Index];
636 Deduced[Index] = TemplateArgument();
637
638 Packs.push_back(Pack);
639 }
640 }
641 }
642 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
643
644 for (auto &Pack : Packs) {
645 if (Info.PendingDeducedPacks.size() > Pack.Index)
646 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
647 else
648 Info.PendingDeducedPacks.resize(Pack.Index + 1);
649 Info.PendingDeducedPacks[Pack.Index] = &Pack;
650
651 if (S.CurrentInstantiationScope) {
652 // If the template argument pack was explicitly specified, add that to
653 // the set of deduced arguments.
654 const TemplateArgument *ExplicitArgs;
655 unsigned NumExplicitArgs;
656 NamedDecl *PartiallySubstitutedPack =
657 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
658 &ExplicitArgs, &NumExplicitArgs);
659 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000660 getDepthAndIndex(PartiallySubstitutedPack) ==
661 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000662 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
663 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000664 }
665 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000666
Richard Smith0a80d572014-05-29 01:12:14 +0000667 ~PackDeductionScope() {
668 for (auto &Pack : Packs)
669 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Richard Smith0a80d572014-05-29 01:12:14 +0000672 /// Move to deducing the next element in each pack that is being deduced.
673 void nextPackElement() {
674 // Capture the deduced template arguments for each parameter pack expanded
675 // by this pack expansion, add them to the list of arguments we've deduced
676 // for that pack, then clear out the deduced argument.
677 for (auto &Pack : Packs) {
678 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000679 if (!Pack.New.empty() || !DeducedArg.isNull()) {
680 while (Pack.New.size() < PackElements)
681 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith0a80d572014-05-29 01:12:14 +0000682 Pack.New.push_back(DeducedArg);
683 DeducedArg = DeducedTemplateArgument();
684 }
685 }
Richard Smith539e8e32017-01-04 01:48:55 +0000686 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000687 }
688
689 /// \brief Finish template argument deduction for a set of argument packs,
690 /// producing the argument packs and checking for consistency with prior
691 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000692 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000693 // Build argument packs for each of the parameter packs expanded by this
694 // pack expansion.
695 for (auto &Pack : Packs) {
696 // Put back the old value for this pack.
697 Deduced[Pack.Index] = Pack.Saved;
698
699 // Build or find a new value for this pack.
700 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000701 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000702 if (Pack.DeferredDeduction.isNull()) {
703 // We were not able to deduce anything for this parameter pack
704 // (because it only appeared in non-deduced contexts), so just
705 // restore the saved argument pack.
706 continue;
707 }
708
709 NewPack = Pack.DeferredDeduction;
710 Pack.DeferredDeduction = TemplateArgument();
711 } else if (Pack.New.empty()) {
712 // If we deduced an empty argument pack, create it now.
713 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
714 } else {
715 TemplateArgument *ArgumentPack =
716 new (S.Context) TemplateArgument[Pack.New.size()];
717 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
718 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000719 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000720 Pack.New[0].wasDeducedFromArrayBound());
721 }
722
723 // Pick where we're going to put the merged pack.
724 DeducedTemplateArgument *Loc;
725 if (Pack.Outer) {
726 if (Pack.Outer->DeferredDeduction.isNull()) {
727 // Defer checking this pack until we have a complete pack to compare
728 // it against.
729 Pack.Outer->DeferredDeduction = NewPack;
730 continue;
731 }
732 Loc = &Pack.Outer->DeferredDeduction;
733 } else {
734 Loc = &Deduced[Pack.Index];
735 }
736
737 // Check the new pack matches any previous value.
738 DeducedTemplateArgument OldPack = *Loc;
739 DeducedTemplateArgument Result =
740 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
741
742 // If we deferred a deduction of this pack, check that one now too.
743 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
744 OldPack = Result;
745 NewPack = Pack.DeferredDeduction;
746 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
747 }
748
749 if (Result.isNull()) {
750 Info.Param =
751 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
752 Info.FirstArg = OldPack;
753 Info.SecondArg = NewPack;
754 return Sema::TDK_Inconsistent;
755 }
756
757 *Loc = Result;
758 }
759
760 return Sema::TDK_Success;
761 }
762
763private:
764 Sema &S;
765 TemplateParameterList *TemplateParams;
766 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
767 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000768 unsigned PackElements = 0;
Richard Smith0a80d572014-05-29 01:12:14 +0000769
770 SmallVector<DeducedPack, 2> Packs;
771};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000772} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000773
Douglas Gregor5499af42011-01-05 23:12:31 +0000774/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000775/// types to the list of argument types, as in the parameter-type-lists of
776/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000777///
778/// \param S The semantic analysis object within which we are deducing
779///
780/// \param TemplateParams The template parameters that we are deducing
781///
782/// \param Params The list of parameter types
783///
784/// \param NumParams The number of types in \c Params
785///
786/// \param Args The list of argument types
787///
788/// \param NumArgs The number of types in \c Args
789///
790/// \param Info information about the template argument deduction itself
791///
792/// \param Deduced the deduced template arguments
793///
794/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
795/// how template argument deduction is performed.
796///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000797/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000798/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000799/// (C++0x [temp.deduct.partial]).
800///
Douglas Gregor5499af42011-01-05 23:12:31 +0000801/// \returns the result of template argument deduction so far. Note that a
802/// "success" result means that template argument deduction has not yet failed,
803/// but it may still fail, later, for other reasons.
804static Sema::TemplateDeductionResult
805DeduceTemplateArguments(Sema &S,
806 TemplateParameterList *TemplateParams,
807 const QualType *Params, unsigned NumParams,
808 const QualType *Args, unsigned NumArgs,
809 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000810 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000811 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000812 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000813 // Fast-path check to see if we have too many/too few arguments.
814 if (NumParams != NumArgs &&
815 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
816 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000817 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
Douglas Gregor5499af42011-01-05 23:12:31 +0000819 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820 // Similarly, if P has a form that contains (T), then each parameter type
821 // Pi of the respective parameter-type- list of P is compared with the
822 // corresponding parameter type Ai of the corresponding parameter-type-list
823 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 unsigned ArgIdx = 0, ParamIdx = 0;
825 for (; ParamIdx != NumParams; ++ParamIdx) {
826 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
829 if (!Expansion) {
830 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
Douglas Gregor5499af42011-01-05 23:12:31 +0000832 // Make sure we have an argument.
833 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000834 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000836 if (isa<PackExpansionType>(Args[ArgIdx])) {
837 // C++0x [temp.deduct.type]p22:
838 // If the original function parameter associated with A is a function
839 // parameter pack and the function parameter associated with P is not
840 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000841 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor5499af42011-01-05 23:12:31 +0000844 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000845 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
846 Params[ParamIdx], Args[ArgIdx],
847 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000848 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000849 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor5499af42011-01-05 23:12:31 +0000851 ++ArgIdx;
852 continue;
853 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000855 // C++0x [temp.deduct.type]p5:
856 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000858 // parameter-declaration-clause.
859 if (ParamIdx + 1 < NumParams)
860 return Sema::TDK_Success;
861
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000866 // comparison deduces template arguments for subsequent positions in the
867 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor5499af42011-01-05 23:12:31 +0000869 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000870 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000871
Douglas Gregor5499af42011-01-05 23:12:31 +0000872 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000873 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000875 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
876 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000877 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000878 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Richard Smith0a80d572014-05-29 01:12:14 +0000880 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882
Douglas Gregor5499af42011-01-05 23:12:31 +0000883 // Build argument packs for each of the parameter packs expanded by this
884 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000885 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5499af42011-01-05 23:12:31 +0000889 // Make sure we don't have any extra arguments.
890 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000891 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor5499af42011-01-05 23:12:31 +0000893 return Sema::TDK_Success;
894}
895
Douglas Gregor1d684c22011-04-28 00:56:09 +0000896/// \brief Determine whether the parameter has qualifiers that are either
897/// inconsistent with or a superset of the argument's qualifiers.
898static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
899 QualType ArgType) {
900 Qualifiers ParamQs = ParamType.getQualifiers();
901 Qualifiers ArgQs = ArgType.getQualifiers();
902
903 if (ParamQs == ArgQs)
904 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000905
Douglas Gregor1d684c22011-04-28 00:56:09 +0000906 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000907 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000908 ParamQs.hasObjCGCAttr())
909 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000910
Douglas Gregor1d684c22011-04-28 00:56:09 +0000911 // Mismatched (but not missing) address spaces.
912 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
913 ParamQs.hasAddressSpace())
914 return true;
915
John McCall31168b02011-06-15 23:02:42 +0000916 // Mismatched (but not missing) Objective-C lifetime qualifiers.
917 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
918 ParamQs.hasObjCLifetime())
919 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000920
Douglas Gregor1d684c22011-04-28 00:56:09 +0000921 // CVR qualifier superset.
922 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
923 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
924 == ParamQs.getCVRQualifiers());
925}
926
Douglas Gregor19a41f12013-04-17 08:45:07 +0000927/// \brief Compare types for equality with respect to possibly compatible
928/// function types (noreturn adjustment, implicit calling conventions). If any
929/// of parameter and argument is not a function, just perform type comparison.
930///
931/// \param Param the template parameter type.
932///
933/// \param Arg the argument type.
934bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
935 CanQualType Arg) {
936 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
937 *ArgFunction = Arg->getAs<FunctionType>();
938
939 // Just compare if not functions.
940 if (!ParamFunction || !ArgFunction)
941 return Param == Arg;
942
Richard Smith3c4f8d22016-10-16 17:54:23 +0000943 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000944 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000945 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000946 return Arg == Context.getCanonicalType(AdjustedParam);
947
948 // FIXME: Compatible calling conventions.
949
950 return Param == Arg;
951}
952
Douglas Gregorcceb9752009-06-26 18:27:22 +0000953/// \brief Deduce the template arguments by comparing the parameter type and
954/// the argument type (C++ [temp.deduct.type]).
955///
Chandler Carruthc1263112010-02-07 21:33:28 +0000956/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000957///
958/// \param TemplateParams the template parameters that we are deducing
959///
960/// \param ParamIn the parameter type
961///
962/// \param ArgIn the argument type
963///
964/// \param Info information about the template argument deduction itself
965///
966/// \param Deduced the deduced template arguments
967///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000968/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000969/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000970///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000971/// \param PartialOrdering Whether we're performing template argument deduction
972/// in the context of partial ordering (C++0x [temp.deduct.partial]).
973///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000974/// \returns the result of template argument deduction so far. Note that a
975/// "success" result means that template argument deduction has not yet failed,
976/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000977static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000978DeduceTemplateArgumentsByTypeMatch(Sema &S,
979 TemplateParameterList *TemplateParams,
980 QualType ParamIn, QualType ArgIn,
981 TemplateDeductionInfo &Info,
982 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
983 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000984 bool PartialOrdering,
985 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000986 // We only want to look at the canonical types, since typedefs and
987 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000988 QualType Param = S.Context.getCanonicalType(ParamIn);
989 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000990
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000991 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000993 if (const PackExpansionType *ArgExpansion
994 = dyn_cast<PackExpansionType>(Arg))
995 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregorb837ea42011-01-11 17:34:58 +0000997 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000998 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999 // Before the partial ordering is done, certain transformations are
1000 // performed on the types used for partial ordering:
1001 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1003 if (ParamRef)
1004 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
Douglas Gregorb837ea42011-01-11 17:34:58 +00001006 // - If A is a reference type, A is replaced by the type referred to.
1007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1008 if (ArgRef)
1009 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Richard Smithed563c22015-02-20 04:45:22 +00001011 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1012 // C++11 [temp.deduct.partial]p9:
1013 // If, for a given type, deduction succeeds in both directions (i.e.,
1014 // the types are identical after the transformations above) and both
1015 // P and A were reference types [...]:
1016 // - if [one type] was an lvalue reference and [the other type] was
1017 // not, [the other type] is not considered to be at least as
1018 // specialized as [the first type]
1019 // - if [one type] is more cv-qualified than [the other type],
1020 // [the other type] is not considered to be at least as specialized
1021 // as [the first type]
1022 // Objective-C ARC adds:
1023 // - [one type] has non-trivial lifetime, [the other type] has
1024 // __unsafe_unretained lifetime, and the types are otherwise
1025 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001026 //
Richard Smithed563c22015-02-20 04:45:22 +00001027 // A is "considered to be at least as specialized" as P iff deduction
1028 // succeeds, so we model this as a deduction failure. Note that
1029 // [the first type] is P and [the other type] is A here; the standard
1030 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001031 Qualifiers ParamQuals = Param.getQualifiers();
1032 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001033 if ((ParamRef->isLValueReferenceType() &&
1034 !ArgRef->isLValueReferenceType()) ||
1035 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1036 (ParamQuals.hasNonTrivialObjCLifetime() &&
1037 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1038 ParamQuals.withoutObjCLifetime() ==
1039 ArgQuals.withoutObjCLifetime())) {
1040 Info.FirstArg = TemplateArgument(ParamIn);
1041 Info.SecondArg = TemplateArgument(ArgIn);
1042 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001043 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Richard Smithed563c22015-02-20 04:45:22 +00001046 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001047 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001049 // version of P.
1050 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001052 // version of A.
1053 Arg = Arg.getUnqualifiedType();
1054 } else {
1055 // C++0x [temp.deduct.call]p4 bullet 1:
1056 // - If the original P is a reference type, the deduced A (i.e., the type
1057 // referred to by the reference) can be more cv-qualified than the
1058 // transformed A.
1059 if (TDF & TDF_ParamWithReferenceType) {
1060 Qualifiers Quals;
1061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001063 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001064 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Douglas Gregor85f240c2011-01-25 17:19:08 +00001067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1068 // C++0x [temp.deduct.type]p10:
1069 // If P and A are function types that originated from deduction when
1070 // taking the address of a function template (14.8.2.2) or when deducing
1071 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 // Ai are parameters of the top-level parameter-type-list of P and A,
1073 // respectively, Pi is adjusted if it is an rvalue reference to a
1074 // cv-unqualified template parameter and Ai is an lvalue reference, in
1075 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001078 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001079 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Douglas Gregor85f240c2011-01-25 17:19:08 +00001081 if (const RValueReferenceType *ParamRef
1082 = Param->getAs<RValueReferenceType>()) {
1083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1084 !ParamRef->getPointeeType().getQualifiers())
1085 if (Arg->isLValueReferenceType())
1086 Param = ParamRef->getPointeeType();
1087 }
1088 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001091 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001092 // A template type argument T, a template template argument TT or a
1093 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001094 // the following forms:
1095 //
1096 // T
1097 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001099 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001100 // Just skip any attempts to deduce from a placeholder type or a parameter
1101 // at a different depth.
1102 if (Arg->isPlaceholderType() ||
1103 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001104 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001105
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001106 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001107 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001108
Douglas Gregor60454822009-07-22 20:02:25 +00001109 // If the argument type is an array type, move the qualifiers up to the
1110 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001111 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001112 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001113 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001114 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001115 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001116 RecanonicalizeArg = true;
1117 }
1118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001120 // The argument type can not be less qualified than the parameter
1121 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001122 if (!(TDF & TDF_IgnoreQualifiers) &&
1123 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001124 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001125 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001126 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001127 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001128 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001129
Richard Smith87d263e2016-12-25 08:05:23 +00001130 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1131 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001132 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001133 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001134
Douglas Gregor1d684c22011-04-28 00:56:09 +00001135 // Remove any qualifiers on the parameter from the deduced type.
1136 // We checked the qualifiers for consistency above.
1137 Qualifiers DeducedQs = DeducedType.getQualifiers();
1138 Qualifiers ParamQs = Param.getQualifiers();
1139 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1140 if (ParamQs.hasObjCGCAttr())
1141 DeducedQs.removeObjCGCAttr();
1142 if (ParamQs.hasAddressSpace())
1143 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001144 if (ParamQs.hasObjCLifetime())
1145 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001146
Douglas Gregore46db902011-06-17 22:11:49 +00001147 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001148 // If template deduction would produce a lifetime qualifier on a type
1149 // that is not a lifetime type, template argument deduction fails.
1150 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1151 !DeducedType->isDependentType()) {
1152 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1153 Info.FirstArg = TemplateArgument(Param);
1154 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001155 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001156 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001157
Douglas Gregora4f2b432011-07-26 14:53:44 +00001158 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001159 // If template deduction would produce an argument type with lifetime type
1160 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001161 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001162 DeducedType->isObjCLifetimeType() &&
1163 !DeducedQs.hasObjCLifetime())
1164 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001165
Douglas Gregor1d684c22011-04-28 00:56:09 +00001166 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1167 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001168
Douglas Gregord6605db2009-07-22 21:30:48 +00001169 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001170 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001171
Richard Smith5f274382016-09-28 23:55:27 +00001172 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001173 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001174 Deduced[Index],
1175 NewDeduced);
1176 if (Result.isNull()) {
1177 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1178 Info.FirstArg = Deduced[Index];
1179 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001183 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001184 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001185 }
1186
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001187 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001188 Info.FirstArg = TemplateArgument(ParamIn);
1189 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001190
Douglas Gregorfb322d82011-01-14 05:11:40 +00001191 // If the parameter is an already-substituted template parameter
1192 // pack, do nothing: we don't know which of its arguments to look
1193 // at, so we have to wait until all of the parameter packs in this
1194 // expansion have arguments.
1195 if (isa<SubstTemplateTypeParmPackType>(Param))
1196 return Sema::TDK_Success;
1197
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001198 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001199 CanQualType CanParam = S.Context.getCanonicalType(Param);
1200 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001201 if (!(TDF & TDF_IgnoreQualifiers)) {
1202 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001203 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001204 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001205 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001206 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001207 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001208 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001209
Douglas Gregor194ea692012-03-11 03:29:50 +00001210 // If the parameter type is not dependent, there is nothing to deduce.
1211 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001212 if (!(TDF & TDF_SkipNonDependent)) {
1213 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1214 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1215 Param != Arg;
1216 if (NonDeduced) {
1217 return Sema::TDK_NonDeducedMismatch;
1218 }
1219 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001220 return Sema::TDK_Success;
1221 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001222 } else if (!Param->isDependentType()) {
1223 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1224 ArgUnqualType = CanArg.getUnqualifiedType();
1225 bool Success = (TDF & TDF_InOverloadResolution)?
1226 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1227 ArgUnqualType) :
1228 ParamUnqualType == ArgUnqualType;
1229 if (Success)
1230 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001231 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001232
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001233 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001234 // Non-canonical types cannot appear here.
1235#define NON_CANONICAL_TYPE(Class, Base) \
1236 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1237#define TYPE(Class, Base)
1238#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001239
Douglas Gregor39c02722011-06-15 16:02:29 +00001240 case Type::TemplateTypeParm:
1241 case Type::SubstTemplateTypeParmPack:
1242 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001243
1244 // These types cannot be dependent, so simply check whether the types are
1245 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001246 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001247 case Type::VariableArray:
1248 case Type::Vector:
1249 case Type::FunctionNoProto:
1250 case Type::Record:
1251 case Type::Enum:
1252 case Type::ObjCObject:
1253 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001254 case Type::ObjCObjectPointer: {
1255 if (TDF & TDF_SkipNonDependent)
1256 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001257
Douglas Gregor194ea692012-03-11 03:29:50 +00001258 if (TDF & TDF_IgnoreQualifiers) {
1259 Param = Param.getUnqualifiedType();
1260 Arg = Arg.getUnqualifiedType();
1261 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001262
Douglas Gregor194ea692012-03-11 03:29:50 +00001263 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1264 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001265
1266 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001267 case Type::Complex:
1268 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001269 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1270 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001271 ComplexArg->getElementType(),
1272 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001273
1274 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001275
1276 // _Atomic T [extension]
1277 case Type::Atomic:
1278 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001279 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001280 cast<AtomicType>(Param)->getValueType(),
1281 AtomicArg->getValueType(),
1282 Info, Deduced, TDF);
1283
1284 return Sema::TDK_NonDeducedMismatch;
1285
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001286 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001287 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001288 QualType PointeeType;
1289 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1290 PointeeType = PointerArg->getPointeeType();
1291 } else if (const ObjCObjectPointerType *PointerArg
1292 = Arg->getAs<ObjCObjectPointerType>()) {
1293 PointeeType = PointerArg->getPointeeType();
1294 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001295 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregorfc516c92009-06-26 23:27:24 +00001298 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1300 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001301 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001302 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001305 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001306 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001307 const LValueReferenceType *ReferenceArg =
1308 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001309 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001310 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001312 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001313 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001314 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001315 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001316
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001317 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001318 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001319 const RValueReferenceType *ReferenceArg =
1320 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001321 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001322 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001323
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001324 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1325 cast<RValueReferenceType>(Param)->getPointeeType(),
1326 ReferenceArg->getPointeeType(),
1327 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001330 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001331 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001332 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001333 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001334 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001336
John McCallf7332682010-08-19 00:20:19 +00001337 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001338 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1339 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1340 IncompleteArrayArg->getElementType(),
1341 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001342 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001343
1344 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001345 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001346 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001347 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001348 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001349 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001350
1351 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001352 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001353 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001354 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001355
John McCallf7332682010-08-19 00:20:19 +00001356 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001357 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1358 ConstantArrayParm->getElementType(),
1359 ConstantArrayArg->getElementType(),
1360 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001361 }
1362
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 // type [i]
1364 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001365 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001366 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001367 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCallf7332682010-08-19 00:20:19 +00001369 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1370
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001371 // Check the element type of the arrays
1372 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001373 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001374 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001375 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1376 DependentArrayParm->getElementType(),
1377 ArrayArg->getElementType(),
1378 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001379 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001380
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001381 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001382 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001383 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001384 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001385 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001386
1387 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001388 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001389 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1390 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001391 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001392 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1393 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001394 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001395 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001396 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001397 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001398 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001399 if (const DependentSizedArrayType *DependentArrayArg
1400 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001401 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001402 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001403 DependentArrayArg->getSizeExpr(),
1404 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001406 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001407 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
1410 // type(*)(T)
1411 // T(*)()
1412 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001414 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001415 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001416 dyn_cast<FunctionProtoType>(Arg);
1417 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001418 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001419
1420 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001421 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001424 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001426 != FunctionProtoArg->getRefQualifier() ||
1427 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001428 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001429
Anders Carlsson2128ec72009-06-08 15:19:08 +00001430 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001431 if (Sema::TemplateDeductionResult Result =
1432 DeduceTemplateArgumentsByTypeMatch(
1433 S, TemplateParams, FunctionProtoParam->getReturnType(),
1434 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001435 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001436
Alp Toker9cacbab2014-01-20 20:26:09 +00001437 return DeduceTemplateArguments(
1438 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1439 FunctionProtoParam->getNumParams(),
1440 FunctionProtoArg->param_type_begin(),
1441 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCalle78aac42010-03-10 03:28:59 +00001444 case Type::InjectedClassName: {
1445 // Treat a template's injected-class-name as if the template
1446 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001447 Param = cast<InjectedClassNameType>(Param)
1448 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001449 assert(isa<TemplateSpecializationType>(Param) &&
1450 "injected class name is not a template specialization type");
1451 // fall through
1452 }
1453
Douglas Gregor705c9002009-06-26 20:57:09 +00001454 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001455 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001456 // TT<T>
1457 // TT<i>
1458 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001459 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001460 const TemplateSpecializationType *SpecParam =
1461 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Richard Smith9b296e32016-04-25 19:09:05 +00001463 // When Arg cannot be a derived class, we can just try to deduce template
1464 // arguments from the template-id.
1465 const RecordType *RecordT = Arg->getAs<RecordType>();
1466 if (!(TDF & TDF_DerivedClass) || !RecordT)
1467 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1468 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Richard Smith9b296e32016-04-25 19:09:05 +00001470 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1471 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001472
Richard Smith9b296e32016-04-25 19:09:05 +00001473 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1474 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Richard Smith9b296e32016-04-25 19:09:05 +00001476 if (Result == Sema::TDK_Success)
1477 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001478
Richard Smith9b296e32016-04-25 19:09:05 +00001479 // We cannot inspect base classes as part of deduction when the type
1480 // is incomplete, so either instantiate any templates necessary to
1481 // complete the type, or skip over it if it cannot be completed.
1482 if (!S.isCompleteType(Info.getLocation(), Arg))
1483 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001484
Richard Smith9b296e32016-04-25 19:09:05 +00001485 // C++14 [temp.deduct.call] p4b3:
1486 // If P is a class and P has the form simple-template-id, then the
1487 // transformed A can be a derived class of the deduced A. Likewise if
1488 // P is a pointer to a class of the form simple-template-id, the
1489 // transformed A can be a pointer to a derived class pointed to by the
1490 // deduced A.
1491 //
1492 // These alternatives are considered only if type deduction would
1493 // otherwise fail. If they yield more than one possible deduced A, the
1494 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001495
Faisal Vali683b0742016-05-19 02:28:21 +00001496 // Reset the incorrectly deduced argument from above.
1497 Deduced = DeducedOrig;
1498
1499 // Use data recursion to crawl through the list of base classes.
1500 // Visited contains the set of nodes we have already visited, while
1501 // ToVisit is our stack of records that we still need to visit.
1502 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1503 SmallVector<const RecordType *, 8> ToVisit;
1504 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001505 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001506 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001507 while (!ToVisit.empty()) {
1508 // Retrieve the next class in the inheritance hierarchy.
1509 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001510
Faisal Vali683b0742016-05-19 02:28:21 +00001511 // If we have already seen this type, skip it.
1512 if (!Visited.insert(NextT).second)
1513 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001514
Faisal Vali683b0742016-05-19 02:28:21 +00001515 // If this is a base class, try to perform template argument
1516 // deduction from it.
1517 if (NextT != RecordT) {
1518 TemplateDeductionInfo BaseInfo(Info.getLocation());
1519 Sema::TemplateDeductionResult BaseResult =
1520 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1521 QualType(NextT, 0), BaseInfo, Deduced);
1522
1523 // If template argument deduction for this base was successful,
1524 // note that we had some success. Otherwise, ignore any deductions
1525 // from this base class.
1526 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001527 // If we've already seen some success, then deduction fails due to
1528 // an ambiguity (temp.deduct.call p5).
1529 if (Successful)
1530 return Sema::TDK_MiscellaneousDeductionFailure;
1531
Faisal Vali683b0742016-05-19 02:28:21 +00001532 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001533 std::swap(SuccessfulDeduced, Deduced);
1534
Faisal Vali683b0742016-05-19 02:28:21 +00001535 Info.Param = BaseInfo.Param;
1536 Info.FirstArg = BaseInfo.FirstArg;
1537 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001538 }
1539
1540 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Faisal Vali683b0742016-05-19 02:28:21 +00001543 // Visit base classes
1544 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1545 for (const auto &Base : Next->bases()) {
1546 assert(Base.getType()->isRecordType() &&
1547 "Base class that isn't a record?");
1548 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1549 }
1550 }
Mike Stump11289f42009-09-09 15:08:12 +00001551
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001552 if (Successful) {
1553 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001554 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001555 }
Richard Smith9b296e32016-04-25 19:09:05 +00001556
Douglas Gregore81f3e72009-07-07 23:09:34 +00001557 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001558 }
1559
Douglas Gregor637d9982009-06-10 23:47:09 +00001560 // T type::*
1561 // T T::*
1562 // T (type::*)()
1563 // type (T::*)()
1564 // type (type::*)(T)
1565 // type (T::*)(T)
1566 // T (type::*)(T)
1567 // T (T::*)()
1568 // T (T::*)(T)
1569 case Type::MemberPointer: {
1570 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1571 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1572 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001573 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001574
David Majnemera381cda2015-11-30 20:34:28 +00001575 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1576 if (ParamPointeeType->isFunctionType())
1577 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1578 /*IsCtorOrDtor=*/false, Info.getLocation());
1579 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1580 if (ArgPointeeType->isFunctionType())
1581 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1582 /*IsCtorOrDtor=*/false, Info.getLocation());
1583
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001584 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001585 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001586 ParamPointeeType,
1587 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001588 Info, Deduced,
1589 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001590 return Result;
1591
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001592 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1593 QualType(MemPtrParam->getClass(), 0),
1594 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001595 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001596 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001597 }
1598
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001599 // (clang extension)
1600 //
Mike Stump11289f42009-09-09 15:08:12 +00001601 // type(^)(T)
1602 // T(^)()
1603 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001604 case Type::BlockPointer: {
1605 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1606 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001607
Anders Carlssona767eee2009-06-12 16:23:10 +00001608 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001609 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001610
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001611 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1612 BlockPtrParam->getPointeeType(),
1613 BlockPtrArg->getPointeeType(),
1614 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001615 }
1616
Douglas Gregor39c02722011-06-15 16:02:29 +00001617 // (clang extension)
1618 //
1619 // T __attribute__(((ext_vector_type(<integral constant>))))
1620 case Type::ExtVector: {
1621 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1622 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1623 // Make sure that the vectors have the same number of elements.
1624 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1625 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001626
Douglas Gregor39c02722011-06-15 16:02:29 +00001627 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001628 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1629 VectorParam->getElementType(),
1630 VectorArg->getElementType(),
1631 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001632 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001633
1634 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001635 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1636 // We can't check the number of elements, since the argument has a
1637 // dependent number of elements. This can only occur during partial
1638 // ordering.
1639
1640 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001641 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1642 VectorParam->getElementType(),
1643 VectorArg->getElementType(),
1644 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001645 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001646
Douglas Gregor39c02722011-06-15 16:02:29 +00001647 return Sema::TDK_NonDeducedMismatch;
1648 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001649
Douglas Gregor39c02722011-06-15 16:02:29 +00001650 // (clang extension)
1651 //
1652 // T __attribute__(((ext_vector_type(N))))
1653 case Type::DependentSizedExtVector: {
1654 const DependentSizedExtVectorType *VectorParam
1655 = cast<DependentSizedExtVectorType>(Param);
1656
1657 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1658 // Perform deduction on the element types.
1659 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001660 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1661 VectorParam->getElementType(),
1662 VectorArg->getElementType(),
1663 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001664 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001665
Douglas Gregor39c02722011-06-15 16:02:29 +00001666 // Perform deduction on the vector size, if we can.
1667 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001668 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001669 if (!NTTP)
1670 return Sema::TDK_Success;
1671
1672 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1673 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001674 // Note that we use the "array bound" rules here; just like in that
1675 // case, we don't have any particular type for the vector size, but
1676 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001677 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001678 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001679 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001680 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001681
1682 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001683 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1684 // Perform deduction on the element types.
1685 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001686 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1687 VectorParam->getElementType(),
1688 VectorArg->getElementType(),
1689 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001690 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001691
Douglas Gregor39c02722011-06-15 16:02:29 +00001692 // Perform deduction on the vector size, if we can.
1693 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001694 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001695 if (!NTTP)
1696 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001697
Richard Smith5f274382016-09-28 23:55:27 +00001698 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1699 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001700 Info, Deduced);
1701 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001702
Douglas Gregor39c02722011-06-15 16:02:29 +00001703 return Sema::TDK_NonDeducedMismatch;
1704 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001705
Douglas Gregor637d9982009-06-10 23:47:09 +00001706 case Type::TypeOfExpr:
1707 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001708 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001709 case Type::UnresolvedUsing:
1710 case Type::Decltype:
1711 case Type::UnaryTransform:
1712 case Type::Auto:
1713 case Type::DependentTemplateSpecialization:
1714 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001715 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001716 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001717 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001718 }
1719
David Blaikiee4d798f2012-01-20 21:50:17 +00001720 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001721}
1722
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001723static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001724DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001725 TemplateParameterList *TemplateParams,
1726 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001727 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001728 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001729 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001730 // If the template argument is a pack expansion, perform template argument
1731 // deduction against the pattern of that expansion. This only occurs during
1732 // partial ordering.
1733 if (Arg.isPackExpansion())
1734 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001736 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001737 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001738 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001739
1740 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001741 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001742 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1743 Param.getAsType(),
1744 Arg.getAsType(),
1745 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001746 Info.FirstArg = Param;
1747 Info.SecondArg = Arg;
1748 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001749
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001750 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001751 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001753 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001754 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001755 Info.FirstArg = Param;
1756 Info.SecondArg = Arg;
1757 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001758
1759 case TemplateArgument::TemplateExpansion:
1760 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001762 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001763 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001764 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001765 return Sema::TDK_Success;
1766
1767 Info.FirstArg = Param;
1768 Info.SecondArg = Arg;
1769 return Sema::TDK_NonDeducedMismatch;
1770
1771 case TemplateArgument::NullPtr:
1772 if (Arg.getKind() == TemplateArgument::NullPtr &&
1773 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001774 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001776 Info.FirstArg = Param;
1777 Info.SecondArg = Arg;
1778 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001780 case TemplateArgument::Integral:
1781 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001782 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001783 return Sema::TDK_Success;
1784
1785 Info.FirstArg = Param;
1786 Info.SecondArg = Arg;
1787 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001788 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001789
1790 if (Arg.getKind() == TemplateArgument::Expression) {
1791 Info.FirstArg = Param;
1792 Info.SecondArg = Arg;
1793 return Sema::TDK_NonDeducedMismatch;
1794 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001795
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001796 Info.FirstArg = Param;
1797 Info.SecondArg = Arg;
1798 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001799
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001800 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001801 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001802 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001803 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001804 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001805 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001806 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001807 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001808 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001809 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001810 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1811 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001812 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001813 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001814 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1815 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001816 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001817 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1818 Arg.getAsDecl(),
1819 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001820 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001822 Info.FirstArg = Param;
1823 Info.SecondArg = Arg;
1824 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001827 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001828 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001829 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001830 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001831 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
David Blaikiee4d798f2012-01-20 21:50:17 +00001834 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001835}
1836
Douglas Gregor7baabef2010-12-22 18:17:10 +00001837/// \brief Determine whether there is a template argument to be used for
1838/// deduction.
1839///
1840/// This routine "expands" argument packs in-place, overriding its input
1841/// parameters so that \c Args[ArgIdx] will be the available template argument.
1842///
1843/// \returns true if there is another template argument (which will be at
1844/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001845static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1846 unsigned &ArgIdx) {
1847 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001848 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
Douglas Gregor7baabef2010-12-22 18:17:10 +00001850 const TemplateArgument &Arg = Args[ArgIdx];
1851 if (Arg.getKind() != TemplateArgument::Pack)
1852 return true;
1853
Richard Smith0bda5b52016-12-23 23:46:56 +00001854 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1855 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001856 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001857 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001858}
1859
Douglas Gregord0ad2942010-12-23 01:24:45 +00001860/// \brief Determine whether the given set of template arguments has a pack
1861/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001862static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1863 bool FoundPackExpansion = false;
1864 for (const auto &A : Args) {
1865 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001866 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001867
1868 if (A.getKind() == TemplateArgument::Pack)
1869 return hasPackExpansionBeforeEnd(A.pack_elements());
1870
1871 if (A.isPackExpansion())
1872 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
Douglas Gregord0ad2942010-12-23 01:24:45 +00001875 return false;
1876}
1877
Douglas Gregor7baabef2010-12-22 18:17:10 +00001878static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001879DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001880 ArrayRef<TemplateArgument> Params,
1881 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001882 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001883 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1884 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001885 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 // If the template argument list of P contains a pack expansion that is not
1887 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001888 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001889 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001890 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001892 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893 // If P has a form that contains <T> or <i>, then each argument Pi of the
1894 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001895 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001896 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001897 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001898 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001899 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900
Douglas Gregor7baabef2010-12-22 18:17:10 +00001901 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001902 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001903 return NumberOfArgumentsMustMatch
1904 ? Sema::TDK_MiscellaneousDeductionFailure
1905 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
Richard Smith26b86ea2016-12-31 21:41:23 +00001907 // C++1z [temp.deduct.type]p9:
1908 // During partial ordering, if Ai was originally a pack expansion [and]
1909 // Pi is not a pack expansion, template argument deduction fails.
1910 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001911 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001914 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001915 = DeduceTemplateArguments(S, TemplateParams,
1916 Params[ParamIdx], Args[ArgIdx],
1917 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918 return Result;
1919
Douglas Gregor7baabef2010-12-22 18:17:10 +00001920 // Move to the next argument.
1921 ++ArgIdx;
1922 continue;
1923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928 // If Pi is a pack expansion, then the pattern of Pi is compared with
1929 // each remaining argument in the template argument list of A. Each
1930 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001931 // template parameter packs expanded by Pi.
1932 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934 // FIXME: If there are no remaining arguments, we can bail out early
1935 // and set any deduced parameter packs to an empty argument pack.
1936 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
Richard Smith0a80d572014-05-29 01:12:14 +00001938 // Prepare to deduce the packs within the pattern.
1939 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001940
1941 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001942 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001943 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001944 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001945 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1948 Info, Deduced))
1949 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Richard Smith0a80d572014-05-29 01:12:14 +00001951 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001954 // Build argument packs for each of the parameter packs expanded by this
1955 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001956 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Douglas Gregor7baabef2010-12-22 18:17:10 +00001960 return Sema::TDK_Success;
1961}
1962
Mike Stump11289f42009-09-09 15:08:12 +00001963static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001964DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001965 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001966 const TemplateArgumentList &ParamList,
1967 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001968 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001969 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001970 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00001971 ArgList.asArray(), Info, Deduced,
1972 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001973}
1974
Douglas Gregor705c9002009-06-26 20:57:09 +00001975/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001976static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00001977 TemplateArgument X,
1978 const TemplateArgument &Y,
1979 bool PackExpansionMatchesPack = false) {
1980 // If we're checking deduced arguments (X) against original arguments (Y),
1981 // we will have flattened packs to non-expansions in X.
1982 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1983 X = X.getPackExpansionPattern();
1984
Douglas Gregor705c9002009-06-26 20:57:09 +00001985 if (X.getKind() != Y.getKind())
1986 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor705c9002009-06-26 20:57:09 +00001988 switch (X.getKind()) {
1989 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001990 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001991
Douglas Gregor705c9002009-06-26 20:57:09 +00001992 case TemplateArgument::Type:
1993 return Context.getCanonicalType(X.getAsType()) ==
1994 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregor705c9002009-06-26 20:57:09 +00001996 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001997 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001998
1999 case TemplateArgument::NullPtr:
2000 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002002 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002003 case TemplateArgument::TemplateExpansion:
2004 return Context.getCanonicalTemplateName(
2005 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2006 Context.getCanonicalTemplateName(
2007 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Douglas Gregor705c9002009-06-26 20:57:09 +00002009 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002010 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002011
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002012 case TemplateArgument::Expression: {
2013 llvm::FoldingSetNodeID XID, YID;
2014 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002016 return XID == YID;
2017 }
Mike Stump11289f42009-09-09 15:08:12 +00002018
Douglas Gregor705c9002009-06-26 20:57:09 +00002019 case TemplateArgument::Pack:
2020 if (X.pack_size() != Y.pack_size())
2021 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002022
2023 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2024 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002025 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002026 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002027 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002028 return false;
2029
2030 return true;
2031 }
2032
David Blaikiee4d798f2012-01-20 21:50:17 +00002033 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002034}
2035
Douglas Gregorca4686d2011-01-04 23:35:54 +00002036/// \brief Allocate a TemplateArgumentLoc where all locations have
2037/// been initialized to the given location.
2038///
James Dennett634962f2012-06-14 21:40:34 +00002039/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002040/// location information for.
2041///
2042/// \param NTTPType For a declaration template argument, the type of
2043/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002044/// argument. Can be null if no type sugar is available to add to the
2045/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002046///
2047/// \param Loc The source location to use for the resulting template
2048/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002049TemplateArgumentLoc
2050Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2051 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052 switch (Arg.getKind()) {
2053 case TemplateArgument::Null:
2054 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002055
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002057 return TemplateArgumentLoc(
2058 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059
Douglas Gregorca4686d2011-01-04 23:35:54 +00002060 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002061 if (NTTPType.isNull())
2062 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002063 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2064 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002065 return TemplateArgumentLoc(TemplateArgument(E), E);
2066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067
Eli Friedmanb826a002012-09-26 02:36:12 +00002068 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002069 if (NTTPType.isNull())
2070 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002071 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2072 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002073 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2074 E);
2075 }
2076
Douglas Gregorca4686d2011-01-04 23:35:54 +00002077 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002078 Expr *E =
2079 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080 return TemplateArgumentLoc(TemplateArgument(E), E);
2081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregor9d802122011-03-02 17:09:35 +00002083 case TemplateArgument::Template:
2084 case TemplateArgument::TemplateExpansion: {
2085 NestedNameSpecifierLocBuilder Builder;
2086 TemplateName Template = Arg.getAsTemplate();
2087 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002088 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002089 else if (QualifiedTemplateName *QTN =
2090 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002091 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002092
Douglas Gregor9d802122011-03-02 17:09:35 +00002093 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002094 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002095 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002096
2097 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002098 Loc, Loc);
2099 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002100
Douglas Gregorca4686d2011-01-04 23:35:54 +00002101 case TemplateArgument::Expression:
2102 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103
Douglas Gregorca4686d2011-01-04 23:35:54 +00002104 case TemplateArgument::Pack:
2105 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
David Blaikiee4d798f2012-01-20 21:50:17 +00002108 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002109}
2110
2111
2112/// \brief Convert the given deduced template argument and add it to the set of
2113/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002114static bool
2115ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2116 DeducedTemplateArgument Arg,
2117 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002118 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002119 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002120 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002121 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2122 unsigned ArgumentPackIndex) {
2123 // Convert the deduced template argument into a template
2124 // argument that we can check, almost as if the user had written
2125 // the template argument explicitly.
2126 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002127 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002128
2129 // Check the template argument, converting it as necessary.
2130 return S.CheckTemplateArgument(
2131 Param, ArgLoc, Template, Template->getLocation(),
2132 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002133 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002134 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2135 : Sema::CTAK_Deduced)
2136 : Sema::CTAK_Specified);
2137 };
2138
Douglas Gregorca4686d2011-01-04 23:35:54 +00002139 if (Arg.getKind() == TemplateArgument::Pack) {
2140 // This is a template argument pack, so check each of its arguments against
2141 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002142 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002143 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002144 // When converting the deduced template argument, append it to the
2145 // general output list. We need to do this so that the template argument
2146 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002147 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002148 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002149 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2150 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002151 if (P.isNull()) {
2152 // We deduced arguments for some elements of this pack, but not for
2153 // all of them. This happens if we get a conditionally-non-deduced
2154 // context in a pack expansion (such as an overload set in one of the
2155 // arguments).
2156 S.Diag(Param->getLocation(),
2157 diag::err_template_arg_deduced_incomplete_pack)
2158 << Arg << Param;
2159 return true;
2160 }
Richard Smith37acb792016-02-03 20:15:01 +00002161 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002162 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163
Douglas Gregor51bc5712011-01-05 20:52:18 +00002164 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002165 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
Richard Smithdf18ee92016-02-03 20:40:30 +00002168 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002169 // itself, in case that substitution fails.
2170 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002171 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002172 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002173 MultiLevelTemplateArgumentList Args(TemplateArgs);
2174
2175 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2176 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2177 NTTP, Output,
2178 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002179 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002180 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2181 NTTP->getDeclName()).isNull())
2182 return true;
2183 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2184 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2185 TTP, Output,
2186 Template->getSourceRange());
2187 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2188 return true;
2189 }
2190 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002191 }
Richard Smith37acb792016-02-03 20:15:01 +00002192
Douglas Gregorca4686d2011-01-04 23:35:54 +00002193 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002194 Output.push_back(
2195 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002196 return false;
2197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198
Richard Smith37acb792016-02-03 20:15:01 +00002199 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002200}
2201
Richard Smith1f5be4d2016-12-21 01:10:31 +00002202// FIXME: This should not be a template, but
2203// ClassTemplatePartialSpecializationDecl sadly does not derive from
2204// TemplateDecl.
2205template<typename TemplateDeclT>
2206static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002207 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002208 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2209 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2210 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2211 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2212 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2213
2214 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2215 NamedDecl *Param = TemplateParams->getParam(I);
2216
2217 if (!Deduced[I].isNull()) {
2218 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002219 // We may have had explicitly-specified template arguments for a
2220 // template parameter pack (that may or may not have been extended
2221 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002222 if (Param->isParameterPack() && CurrentInstantiationScope &&
2223 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2224 // Forget the partially-substituted pack; its substitution is now
2225 // complete.
2226 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2227 // We still need to check the argument in case it was extended by
2228 // deduction.
2229 } else {
2230 // We have already fully type-checked and converted this
2231 // argument, because it was explicitly-specified. Just record the
2232 // presence of this argument.
2233 Builder.push_back(Deduced[I]);
2234 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002235 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002236 }
2237
Richard Smith9c0c9862017-01-05 20:27:28 +00002238 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002239 // checked and converted.
2240 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002241 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002242 Info.Param = makeTemplateParameter(Param);
2243 // FIXME: These template arguments are temporary. Free them!
2244 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2245 return Sema::TDK_SubstitutionFailure;
2246 }
2247
2248 continue;
2249 }
2250
2251 // C++0x [temp.arg.explicit]p3:
2252 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2253 // be deduced to an empty sequence of template arguments.
2254 // FIXME: Where did the word "trailing" come from?
2255 if (Param->isTemplateParameterPack()) {
2256 // We may have had explicitly-specified template arguments for this
2257 // template parameter pack. If so, our empty deduction extends the
2258 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2259 const TemplateArgument *ExplicitArgs;
2260 unsigned NumExplicitArgs;
2261 if (CurrentInstantiationScope &&
2262 CurrentInstantiationScope->getPartiallySubstitutedPack(
2263 &ExplicitArgs, &NumExplicitArgs) == Param) {
2264 Builder.push_back(TemplateArgument(
2265 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2266
2267 // Forget the partially-substituted pack; its substitution is now
2268 // complete.
2269 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2270 } else {
2271 // Go through the motions of checking the empty argument pack against
2272 // the parameter pack.
2273 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002274 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2275 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002276 Info.Param = makeTemplateParameter(Param);
2277 // FIXME: These template arguments are temporary. Free them!
2278 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2279 return Sema::TDK_SubstitutionFailure;
2280 }
2281 }
2282 continue;
2283 }
2284
2285 // Substitute into the default template argument, if available.
2286 bool HasDefaultArg = false;
2287 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2288 if (!TD) {
2289 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2290 return Sema::TDK_Incomplete;
2291 }
2292
2293 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2294 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2295 HasDefaultArg);
2296
2297 // If there was no default argument, deduction is incomplete.
2298 if (DefArg.getArgument().isNull()) {
2299 Info.Param = makeTemplateParameter(
2300 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2301 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2302 if (PartialOverloading) break;
2303
2304 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2305 : Sema::TDK_Incomplete;
2306 }
2307
2308 // Check whether we can actually use the default argument.
2309 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2310 TD->getSourceRange().getEnd(), 0, Builder,
2311 Sema::CTAK_Specified)) {
2312 Info.Param = makeTemplateParameter(
2313 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2314 // FIXME: These template arguments are temporary. Free them!
2315 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2316 return Sema::TDK_SubstitutionFailure;
2317 }
2318
2319 // If we get here, we successfully used the default template argument.
2320 }
2321
2322 return Sema::TDK_Success;
2323}
2324
Richard Smith0da6dc42016-12-24 16:40:51 +00002325DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2326 if (auto *DC = dyn_cast<DeclContext>(D))
2327 return DC;
2328 return D->getDeclContext();
2329}
2330
2331template<typename T> struct IsPartialSpecialization {
2332 static constexpr bool value = false;
2333};
2334template<>
2335struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2336 static constexpr bool value = true;
2337};
2338template<>
2339struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2340 static constexpr bool value = true;
2341};
2342
2343/// Complete template argument deduction for a partial specialization.
2344template <typename T>
2345static typename std::enable_if<IsPartialSpecialization<T>::value,
2346 Sema::TemplateDeductionResult>::type
2347FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002348 Sema &S, T *Partial, bool IsPartialOrdering,
2349 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002350 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2351 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002352 // Unevaluated SFINAE context.
2353 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002354 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355
Richard Smith0da6dc42016-12-24 16:40:51 +00002356 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002357
2358 // C++ [temp.deduct.type]p2:
2359 // [...] or if any template argument remains neither deduced nor
2360 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002361 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002362 if (auto Result = ConvertDeducedTemplateArguments(
2363 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002364 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002365
Douglas Gregor684268d2010-04-29 06:21:43 +00002366 // Form the template argument list from the deduced template arguments.
2367 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002368 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002369
Douglas Gregor684268d2010-04-29 06:21:43 +00002370 Info.reset(DeducedArgumentList);
2371
2372 // Substitute the deduced template arguments into the template
2373 // arguments of the class template partial specialization, and
2374 // verify that the instantiated template arguments are both valid
2375 // and are equivalent to the template arguments originally provided
2376 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002377 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002378 auto *Template = Partial->getSpecializedTemplate();
2379 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2380 Partial->getTemplateArgsAsWritten();
2381 const TemplateArgumentLoc *PartialTemplateArgs =
2382 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002383
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002384 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2385 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002386
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002387 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002388 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2389 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2390 if (ParamIdx >= Partial->getTemplateParameters()->size())
2391 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2392
Richard Smith0da6dc42016-12-24 16:40:51 +00002393 Decl *Param = const_cast<NamedDecl *>(
2394 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002395 Info.Param = makeTemplateParameter(Param);
2396 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2397 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002398 }
2399
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002400 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002401 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2402 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002403 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404
Richard Smith0da6dc42016-12-24 16:40:51 +00002405 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002406 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002407 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002408 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002409 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002410 Info.FirstArg = TemplateArgs[I];
2411 Info.SecondArg = InstArg;
2412 return Sema::TDK_NonDeducedMismatch;
2413 }
2414 }
2415
2416 if (Trap.hasErrorOccurred())
2417 return Sema::TDK_SubstitutionFailure;
2418
2419 return Sema::TDK_Success;
2420}
2421
Richard Smith0e617ec2016-12-27 07:56:27 +00002422/// Complete template argument deduction for a class or variable template,
2423/// when partial ordering against a partial specialization.
2424// FIXME: Factor out duplication with partial specialization version above.
2425Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2426 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2427 const TemplateArgumentList &TemplateArgs,
2428 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2429 TemplateDeductionInfo &Info) {
2430 // Unevaluated SFINAE context.
2431 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2432 Sema::SFINAETrap Trap(S);
2433
2434 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2435
2436 // C++ [temp.deduct.type]p2:
2437 // [...] or if any template argument remains neither deduced nor
2438 // explicitly specified, template argument deduction fails.
2439 SmallVector<TemplateArgument, 4> Builder;
2440 if (auto Result = ConvertDeducedTemplateArguments(
2441 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2442 return Result;
2443
2444 // Check that we produced the correct argument list.
2445 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2446 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2447 TemplateArgument InstArg = Builder[I];
2448 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2449 /*PackExpansionMatchesPack*/true)) {
2450 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2451 Info.FirstArg = TemplateArgs[I];
2452 Info.SecondArg = InstArg;
2453 return Sema::TDK_NonDeducedMismatch;
2454 }
2455 }
2456
2457 if (Trap.hasErrorOccurred())
2458 return Sema::TDK_SubstitutionFailure;
2459
2460 return Sema::TDK_Success;
2461}
2462
2463
Douglas Gregor170bc422009-06-12 22:31:52 +00002464/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002465/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002466/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002467Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002468Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002469 const TemplateArgumentList &TemplateArgs,
2470 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002471 if (Partial->isInvalidDecl())
2472 return TDK_Invalid;
2473
Douglas Gregor170bc422009-06-12 22:31:52 +00002474 // C++ [temp.class.spec.match]p2:
2475 // A partial specialization matches a given actual template
2476 // argument list if the template arguments of the partial
2477 // specialization can be deduced from the actual template argument
2478 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002479
2480 // Unevaluated SFINAE context.
2481 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002482 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002483
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002484 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002485 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002486 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002487 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002488 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002489 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002490 TemplateArgs, Info, Deduced))
2491 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002492
Richard Smith80934652012-07-16 01:09:10 +00002493 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002494 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2495 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002496 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002497 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002498
Douglas Gregore1416332009-06-14 08:02:22 +00002499 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002500 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002501
Richard Smith87d263e2016-12-25 08:05:23 +00002502 return ::FinishTemplateArgumentDeduction(
2503 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002504}
Douglas Gregor91772d12009-06-13 00:26:55 +00002505
Larisse Voufo39a1e502013-08-06 01:03:05 +00002506/// \brief Perform template argument deduction to determine whether
2507/// the given template arguments match the given variable template
2508/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002509Sema::TemplateDeductionResult
2510Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2511 const TemplateArgumentList &TemplateArgs,
2512 TemplateDeductionInfo &Info) {
2513 if (Partial->isInvalidDecl())
2514 return TDK_Invalid;
2515
2516 // C++ [temp.class.spec.match]p2:
2517 // A partial specialization matches a given actual template
2518 // argument list if the template arguments of the partial
2519 // specialization can be deduced from the actual template argument
2520 // list (14.8.2).
2521
2522 // Unevaluated SFINAE context.
2523 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2524 SFINAETrap Trap(*this);
2525
2526 SmallVector<DeducedTemplateArgument, 4> Deduced;
2527 Deduced.resize(Partial->getTemplateParameters()->size());
2528 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2529 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2530 TemplateArgs, Info, Deduced))
2531 return Result;
2532
2533 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002534 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2535 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002536 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002537 return TDK_InstantiationDepth;
2538
2539 if (Trap.hasErrorOccurred())
2540 return Sema::TDK_SubstitutionFailure;
2541
Richard Smith87d263e2016-12-25 08:05:23 +00002542 return ::FinishTemplateArgumentDeduction(
2543 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002544}
2545
Douglas Gregorfc516c92009-06-26 23:27:24 +00002546/// \brief Determine whether the given type T is a simple-template-id type.
2547static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002548 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002549 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002550 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregorfc516c92009-06-26 23:27:24 +00002552 return false;
2553}
Douglas Gregor9b146582009-07-08 20:55:45 +00002554
2555/// \brief Substitute the explicitly-provided template arguments into the
2556/// given function template according to C++ [temp.arg.explicit].
2557///
2558/// \param FunctionTemplate the function template into which the explicit
2559/// template arguments will be substituted.
2560///
James Dennett634962f2012-06-14 21:40:34 +00002561/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002562/// arguments.
2563///
Mike Stump11289f42009-09-09 15:08:12 +00002564/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002565/// with the converted and checked explicit template arguments.
2566///
Mike Stump11289f42009-09-09 15:08:12 +00002567/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002568/// parameters.
2569///
2570/// \param FunctionType if non-NULL, the result type of the function template
2571/// will also be instantiated and the pointed-to value will be updated with
2572/// the instantiated function type.
2573///
2574/// \param Info if substitution fails for any reason, this object will be
2575/// populated with more information about the failure.
2576///
2577/// \returns TDK_Success if substitution was successful, or some failure
2578/// condition.
2579Sema::TemplateDeductionResult
2580Sema::SubstituteExplicitTemplateArguments(
2581 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002582 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2584 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002585 QualType *FunctionType,
2586 TemplateDeductionInfo &Info) {
2587 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2588 TemplateParameterList *TemplateParams
2589 = FunctionTemplate->getTemplateParameters();
2590
John McCall6b51f282009-11-23 01:53:49 +00002591 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002592 // No arguments to substitute; just copy over the parameter types and
2593 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002594 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002595 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregor9b146582009-07-08 20:55:45 +00002597 if (FunctionType)
2598 *FunctionType = Function->getType();
2599 return TDK_Success;
2600 }
Mike Stump11289f42009-09-09 15:08:12 +00002601
Eli Friedman77dcc722012-02-08 03:07:05 +00002602 // Unevaluated SFINAE context.
2603 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002604 SFINAETrap Trap(*this);
2605
Douglas Gregor9b146582009-07-08 20:55:45 +00002606 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002607 // Template arguments that are present shall be specified in the
2608 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002609 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002610 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002611 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002612
2613 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002614 // explicitly-specified template arguments against this function template,
2615 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002616 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002617 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2618 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002619 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2620 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002621 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002622 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002623
Douglas Gregor9b146582009-07-08 20:55:45 +00002624 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002625 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002626 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002627 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002628 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002629 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002630 if (Index >= TemplateParams->size())
2631 Index = TemplateParams->size() - 1;
2632 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002633 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002634 }
Mike Stump11289f42009-09-09 15:08:12 +00002635
Douglas Gregor9b146582009-07-08 20:55:45 +00002636 // Form the template argument list from the explicitly-specified
2637 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002638 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002639 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002640 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002641
John McCall036855a2010-10-12 19:40:14 +00002642 // Template argument deduction and the final substitution should be
2643 // done in the context of the templated declaration. Explicit
2644 // argument substitution, on the other hand, needs to happen in the
2645 // calling context.
2646 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2647
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002649 // note that the template argument pack is partially substituted and record
2650 // the explicit template arguments. They'll be used as part of deduction
2651 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002652 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2653 const TemplateArgument &Arg = Builder[I];
2654 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002655 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002657 Arg.pack_begin(),
2658 Arg.pack_size());
2659 break;
2660 }
2661 }
2662
Richard Smith5e580292012-02-10 09:58:53 +00002663 const FunctionProtoType *Proto
2664 = Function->getType()->getAs<FunctionProtoType>();
2665 assert(Proto && "Function template does not have a prototype?");
2666
Richard Smith70b13042015-01-09 01:19:56 +00002667 // Isolate our substituted parameters from our caller.
2668 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2669
John McCallc8e321d2016-03-01 02:09:25 +00002670 ExtParameterInfoBuilder ExtParamInfos;
2671
Douglas Gregor9b146582009-07-08 20:55:45 +00002672 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002673 // explicitly-specified template arguments. If the function has a trailing
2674 // return type, substitute it after the arguments to ensure we substitute
2675 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002676 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002677 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002678 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002679 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002680 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002681 return TDK_SubstitutionFailure;
2682 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002683
Richard Smith5e580292012-02-10 09:58:53 +00002684 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002685 QualType ResultType;
2686 {
2687 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002688 // If a declaration declares a member function or member function
2689 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002690 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002691 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002692 // declarator.
2693 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002694 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2696 ThisContext = Method->getParent();
2697 ThisTypeQuals = Method->getTypeQualifiers();
2698 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002699
Douglas Gregor3024f072012-04-16 07:05:22 +00002700 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002701 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002702
2703 ResultType =
2704 SubstType(Proto->getReturnType(),
2705 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2706 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002707 if (ResultType.isNull() || Trap.hasErrorOccurred())
2708 return TDK_SubstitutionFailure;
2709 }
John McCallc8e321d2016-03-01 02:09:25 +00002710
Richard Smith5e580292012-02-10 09:58:53 +00002711 // Instantiate the types of each of the function parameters given the
2712 // explicitly-specified template arguments if we didn't do so earlier.
2713 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002714 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002715 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002716 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002717 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002718 return TDK_SubstitutionFailure;
2719
Douglas Gregor9b146582009-07-08 20:55:45 +00002720 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002721 auto EPI = Proto->getExtProtoInfo();
2722 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002723 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002724 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002725 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002726 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002727 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2728 return TDK_SubstitutionFailure;
2729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor9b146582009-07-08 20:55:45 +00002731 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002732 // Trailing template arguments that can be deduced (14.8.2) may be
2733 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002734 // template arguments can be deduced, they may all be omitted; in this
2735 // case, the empty template argument list <> itself may also be omitted.
2736 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002737 // Take all of the explicitly-specified arguments and put them into
2738 // the set of deduced template arguments. Explicitly-specified
2739 // parameter packs, however, will be set to NULL since the deduction
2740 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002741 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002742 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2743 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2744 if (Arg.getKind() == TemplateArgument::Pack)
2745 Deduced.push_back(DeducedTemplateArgument());
2746 else
2747 Deduced.push_back(Arg);
2748 }
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregor9b146582009-07-08 20:55:45 +00002750 return TDK_Success;
2751}
2752
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002753/// \brief Check whether the deduced argument type for a call to a function
2754/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002755static bool
2756CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002757 QualType DeducedA) {
2758 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002759
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002760 QualType A = OriginalArg.OriginalArgType;
2761 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002762
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002763 // Check for type equality (top-level cv-qualifiers are ignored).
2764 if (Context.hasSameUnqualifiedType(A, DeducedA))
2765 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002766
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002767 // Strip off references on the argument types; they aren't needed for
2768 // the following checks.
2769 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2770 DeducedA = DeducedARef->getPointeeType();
2771 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2772 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002773
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002774 // C++ [temp.deduct.call]p4:
2775 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002776 // - If the original P is a reference type, the deduced A (i.e., the
2777 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002778 // the transformed A.
2779 if (const ReferenceType *OriginalParamRef
2780 = OriginalParamType->getAs<ReferenceType>()) {
2781 // We don't want to keep the reference around any more.
2782 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002783
Richard Smith1be59c52016-10-22 01:32:19 +00002784 // FIXME: Resolve core issue (no number yet): if the original P is a
2785 // reference type and the transformed A is function type "noexcept F",
2786 // the deduced A can be F.
2787 QualType Tmp;
2788 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2789 return false;
2790
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002791 Qualifiers AQuals = A.getQualifiers();
2792 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002793
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002794 // Under Objective-C++ ARC, the deduced type may have implicitly
2795 // been given strong or (when dealing with a const reference)
2796 // unsafe_unretained lifetime. If so, update the original
2797 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002798 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002799 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2800 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2801 (DeducedAQuals.hasConst() &&
2802 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2803 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002804 }
2805
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002806 if (AQuals == DeducedAQuals) {
2807 // Qualifiers match; there's nothing to do.
2808 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002809 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002810 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002811 // Qualifiers are compatible, so have the argument type adopt the
2812 // deduced argument type's qualifiers as if we had performed the
2813 // qualification conversion.
2814 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2815 }
2816 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002817
2818 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002819 // type that can be converted to the deduced A via a function pointer
2820 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002821 //
Richard Smith1be59c52016-10-22 01:32:19 +00002822 // Also allow conversions which merely strip __attribute__((noreturn)) from
2823 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002824 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002825 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002826 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002827 (S.IsQualificationConversion(A, DeducedA, false,
2828 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002829 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002830 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002831
Simon Pilgrim728134c2016-08-12 11:43:57 +00002832 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002833 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002834 // [...] Likewise, if P is a pointer to a class of the form
2835 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002836 // derived class pointed to by the deduced A.
2837 if (const PointerType *OriginalParamPtr
2838 = OriginalParamType->getAs<PointerType>()) {
2839 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2840 if (const PointerType *APtr = A->getAs<PointerType>()) {
2841 if (A->getPointeeType()->isRecordType()) {
2842 OriginalParamType = OriginalParamPtr->getPointeeType();
2843 DeducedA = DeducedAPtr->getPointeeType();
2844 A = APtr->getPointeeType();
2845 }
2846 }
2847 }
2848 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002849
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002850 if (Context.hasSameUnqualifiedType(A, DeducedA))
2851 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002852
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002853 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002854 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002855 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002856
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002857 return true;
2858}
2859
Richard Smithc92d2062017-01-05 23:02:44 +00002860/// Find the pack index for a particular parameter index in an instantiation of
2861/// a function template with specific arguments.
2862///
2863/// \return The pack index for whichever pack produced this parameter, or -1
2864/// if this was not produced by a parameter. Intended to be used as the
2865/// ArgumentPackSubstitutionIndex for further substitutions.
2866// FIXME: We should track this in OriginalCallArgs so we don't need to
2867// reconstruct it here.
2868static unsigned getPackIndexForParam(Sema &S,
2869 FunctionTemplateDecl *FunctionTemplate,
2870 const MultiLevelTemplateArgumentList &Args,
2871 unsigned ParamIdx) {
2872 unsigned Idx = 0;
2873 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2874 if (PD->isParameterPack()) {
2875 unsigned NumExpansions =
2876 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2877 if (Idx + NumExpansions > ParamIdx)
2878 return ParamIdx - Idx;
2879 Idx += NumExpansions;
2880 } else {
2881 if (Idx == ParamIdx)
2882 return -1; // Not a pack expansion
2883 ++Idx;
2884 }
2885 }
2886
2887 llvm_unreachable("parameter index would not be produced from template");
2888}
2889
Mike Stump11289f42009-09-09 15:08:12 +00002890/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002891/// checking the deduced template arguments for completeness and forming
2892/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002893///
2894/// \param OriginalCallArgs If non-NULL, the original call arguments against
2895/// which the deduced argument types should be compared.
Renato Golindad96d62017-01-02 11:15:42 +00002896Sema::TemplateDeductionResult
2897Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2898 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2899 unsigned NumExplicitlySpecified,
2900 FunctionDecl *&Specialization,
2901 TemplateDeductionInfo &Info,
2902 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2903 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002904 // Unevaluated SFINAE context.
2905 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002906 SFINAETrap Trap(*this);
2907
Douglas Gregor9b146582009-07-08 20:55:45 +00002908 // Enter a new template instantiation context while we instantiate the
2909 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002910 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002911 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2912 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002913 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2914 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002915 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002916 return TDK_InstantiationDepth;
2917
John McCalle23b8712010-04-29 01:18:58 +00002918 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002919
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002920 // C++ [temp.deduct.type]p2:
2921 // [...] or if any template argument remains neither deduced nor
2922 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002923 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002924 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002925 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002926 CurrentInstantiationScope, NumExplicitlySpecified,
2927 PartialOverloading))
2928 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002929
2930 // Form the template argument list from the deduced template arguments.
2931 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002932 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002933 Info.reset(DeducedArgumentList);
2934
Mike Stump11289f42009-09-09 15:08:12 +00002935 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002936 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002937 DeclContext *Owner = FunctionTemplate->getDeclContext();
2938 if (FunctionTemplate->getFriendObjectKind())
2939 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00002940 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00002941 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00002942 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002943 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002944 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002945
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002946 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002947 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948
Mike Stump11289f42009-09-09 15:08:12 +00002949 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002950 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002951 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2952 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002953 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002954
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002955 // There may have been an error that did not prevent us from constructing a
2956 // declaration. Mark the declaration invalid and return with a substitution
2957 // failure.
2958 if (Trap.hasErrorOccurred()) {
2959 Specialization->setInvalidDecl(true);
2960 return TDK_SubstitutionFailure;
2961 }
2962
Douglas Gregore65aacb2011-06-16 16:50:48 +00002963 if (OriginalCallArgs) {
2964 // C++ [temp.deduct.call]p4:
2965 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002966 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002967 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00002968 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002969 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2970 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00002971
Richard Smithc92d2062017-01-05 23:02:44 +00002972 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002973 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00002974 // FIXME: This presumably means a pack ended up smaller than we
2975 // expected while deducing. Should this not result in deduction
2976 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00002977 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002978
Richard Smithc92d2062017-01-05 23:02:44 +00002979 QualType DeducedA;
2980 if (!OriginalArg.DecomposedParam) {
2981 // P is one of the function parameters, just look up its substituted
2982 // type.
2983 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2984 } else {
2985 // P is a decomposed element of a parameter corresponding to a
2986 // braced-init-list argument. Substitute back into P to find the
2987 // deduced A.
2988 QualType &CacheEntry =
2989 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
2990 if (CacheEntry.isNull()) {
2991 ArgumentPackSubstitutionIndexRAII PackIndex(
2992 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
2993 ParamIdx));
2994 CacheEntry =
2995 SubstType(OriginalArg.OriginalParamType, SubstArgs,
2996 Specialization->getTypeSpecStartLoc(),
2997 Specialization->getDeclName());
2998 }
2999 DeducedA = CacheEntry;
3000 }
3001
Richard Smith9b534542015-12-31 02:02:54 +00003002 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3003 Info.FirstArg = TemplateArgument(DeducedA);
3004 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3005 Info.CallArgIndex = OriginalArg.ArgIdx;
Richard Smithc92d2062017-01-05 23:02:44 +00003006 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3007 : TDK_DeducedMismatch;
Richard Smith9b534542015-12-31 02:02:54 +00003008 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003009 }
3010 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003011
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003012 // If we suppressed any diagnostics while performing template argument
3013 // deduction, and if we haven't already instantiated this declaration,
3014 // keep track of these diagnostics. They'll be emitted if this specialization
3015 // is actually used.
3016 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003017 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003018 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3019 if (Pos == SuppressedDiagnostics.end())
3020 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3021 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003023
Mike Stump11289f42009-09-09 15:08:12 +00003024 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003025}
3026
John McCall8d08b9b2010-08-27 09:08:28 +00003027/// Gets the type of a function for template-argument-deducton
3028/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003029static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003030 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003031 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003032 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003033 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003034 return QualType();
3035
John McCallc1f69982010-02-02 02:21:27 +00003036 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003037 if (Method->isInstance()) {
3038 // An instance method that's referenced in a form that doesn't
3039 // look like a member pointer is just invalid.
3040 if (!R.HasFormOfMemberPointer) return QualType();
3041
Richard Smith2a7d4812013-05-04 07:00:32 +00003042 return S.Context.getMemberPointerType(Fn->getType(),
3043 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003044 }
3045
3046 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003047 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003048}
3049
3050/// Apply the deduction rules for overload sets.
3051///
3052/// \return the null type if this argument should be treated as an
3053/// undeduced context
3054static QualType
3055ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003056 Expr *Arg, QualType ParamType,
3057 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
John McCall8d08b9b2010-08-27 09:08:28 +00003059 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003060
John McCall8d08b9b2010-08-27 09:08:28 +00003061 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003062
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003063 // C++0x [temp.deduct.call]p4
3064 unsigned TDF = 0;
3065 if (ParamWasReference)
3066 TDF |= TDF_ParamWithReferenceType;
3067 if (R.IsAddressOfOperand)
3068 TDF |= TDF_IgnoreQualifiers;
3069
John McCallc1f69982010-02-02 02:21:27 +00003070 // C++0x [temp.deduct.call]p6:
3071 // When P is a function type, pointer to function type, or pointer
3072 // to member function type:
3073
3074 if (!ParamType->isFunctionType() &&
3075 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003076 !ParamType->isMemberFunctionPointerType()) {
3077 if (Ovl->hasExplicitTemplateArgs()) {
3078 // But we can still look for an explicit specialization.
3079 if (FunctionDecl *ExplicitSpec
3080 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003081 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003082 }
John McCallc1f69982010-02-02 02:21:27 +00003083
George Burgess IVcc2f3552016-03-19 21:51:45 +00003084 DeclAccessPair DAP;
3085 if (FunctionDecl *Viable =
3086 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3087 return GetTypeOfFunction(S, R, Viable);
3088
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003089 return QualType();
3090 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003091
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003092 // Gather the explicit template arguments, if any.
3093 TemplateArgumentListInfo ExplicitTemplateArgs;
3094 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003095 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003096 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003097 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3098 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003099 NamedDecl *D = (*I)->getUnderlyingDecl();
3100
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003101 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3102 // - If the argument is an overload set containing one or more
3103 // function templates, the parameter is treated as a
3104 // non-deduced context.
3105 if (!Ovl->hasExplicitTemplateArgs())
3106 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003107
3108 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003109 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003110 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003111 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3112 Specialization, Info))
3113 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003114
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003115 D = Specialization;
3116 }
John McCallc1f69982010-02-02 02:21:27 +00003117
3118 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003119 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003120 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003121
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003122 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003124 ArgType->isFunctionType())
3125 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126
John McCallc1f69982010-02-02 02:21:27 +00003127 // - If the argument is an overload set (not containing function
3128 // templates), trial argument deduction is attempted using each
3129 // of the members of the set. If deduction succeeds for only one
3130 // of the overload set members, that member is used as the
3131 // argument value for the deduction. If deduction succeeds for
3132 // more than one member of the overload set the parameter is
3133 // treated as a non-deduced context.
3134
3135 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3136 // Type deduction is done independently for each P/A pair, and
3137 // the deduced template argument values are then combined.
3138 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003139 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003140 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003141 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003142 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003143 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3144 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003145 if (Result) continue;
3146 if (!Match.isNull()) return QualType();
3147 Match = ArgType;
3148 }
3149
3150 return Match;
3151}
3152
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003154/// described in C++ [temp.deduct.call].
3155///
3156/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003157/// argument deduction based on this P/A pair because the argument is an
3158/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3160 TemplateParameterList *TemplateParams,
3161 QualType &ParamType,
3162 QualType &ArgType,
3163 Expr *Arg,
3164 unsigned &TDF) {
3165 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003166 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003167 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003168 if (ParamType.hasQualifiers())
3169 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003170
3171 // [...] If P is a reference type, the type referred to by P is
3172 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003173 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003174 if (ParamRefType)
3175 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003176
Nathan Sidwell96090022015-01-16 15:20:14 +00003177 // Overload sets usually make this parameter an undeduced context,
3178 // but there are sometimes special circumstances. Typically
3179 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003180 if (ArgType == S.Context.OverloadTy) {
3181 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3182 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003183 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003184 if (ArgType.isNull())
3185 return true;
3186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor7825bf32011-01-06 22:09:01 +00003188 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003189 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003190 if (ArgType->isIncompleteArrayType()) {
3191 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003192 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003193 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003194
Douglas Gregor7825bf32011-01-06 22:09:01 +00003195 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003196 // If P is an rvalue reference to a cv-unqualified template
3197 // parameter and the argument is an lvalue, the type "lvalue
3198 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003199 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003200 !ParamType.getQualifiers() &&
3201 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003202 Arg->isLValue())
3203 ArgType = S.Context.getLValueReferenceType(ArgType);
3204 } else {
3205 // C++ [temp.deduct.call]p2:
3206 // If P is not a reference type:
3207 // - If A is an array type, the pointer type produced by the
3208 // array-to-pointer standard conversion (4.2) is used in place of
3209 // A for type deduction; otherwise,
3210 if (ArgType->isArrayType())
3211 ArgType = S.Context.getArrayDecayedType(ArgType);
3212 // - If A is a function type, the pointer type produced by the
3213 // function-to-pointer standard conversion (4.3) is used in place
3214 // of A for type deduction; otherwise,
3215 else if (ArgType->isFunctionType())
3216 ArgType = S.Context.getPointerType(ArgType);
3217 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003218 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003219 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003220 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003221 }
3222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223
Douglas Gregor7825bf32011-01-06 22:09:01 +00003224 // C++0x [temp.deduct.call]p4:
3225 // In general, the deduction process attempts to find template argument
3226 // values that will make the deduced A identical to A (after the type A
3227 // is transformed as described above). [...]
3228 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229
Douglas Gregor7825bf32011-01-06 22:09:01 +00003230 // - If the original P is a reference type, the deduced A (i.e., the
3231 // type referred to by the reference) can be more cv-qualified than
3232 // the transformed A.
3233 if (ParamRefType)
3234 TDF |= TDF_ParamWithReferenceType;
3235 // - The transformed A can be another pointer or pointer to member
3236 // type that can be converted to the deduced A via a qualification
3237 // conversion (4.4).
3238 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3239 ArgType->isObjCObjectPointerType())
3240 TDF |= TDF_IgnoreQualifiers;
3241 // - If P is a class and P has the form simple-template-id, then the
3242 // transformed A can be a derived class of the deduced A. Likewise,
3243 // if P is a pointer to a class of the form simple-template-id, the
3244 // transformed A can be a pointer to a derived class pointed to by
3245 // the deduced A.
3246 if (isSimpleTemplateIdType(ParamType) ||
3247 (isa<PointerType>(ParamType) &&
3248 isSimpleTemplateIdType(
3249 ParamType->getAs<PointerType>()->getPointeeType())))
3250 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Douglas Gregor7825bf32011-01-06 22:09:01 +00003252 return false;
3253}
3254
Nico Weberc153d242014-07-28 00:02:09 +00003255static bool
3256hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3257 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003258
Richard Smith707eab62017-01-05 04:08:31 +00003259static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Hubert Tong3280b332015-06-25 00:25:49 +00003260 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3261 Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003262 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3263 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003264 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003265
3266/// \brief Attempt template argument deduction from an initializer list
3267/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003268static Sema::TemplateDeductionResult DeduceFromInitializerList(
3269 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3270 InitListExpr *ILE, TemplateDeductionInfo &Info,
3271 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003272 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3273 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003274 // C++ [temp.deduct.call]p1: (CWG 1591)
3275 // If removing references and cv-qualifiers from P gives
3276 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3277 // a non-empty initializer list, then deduction is performed instead for
3278 // each element of the initializer list, taking P0 as a function template
3279 // parameter type and the initializer element as its argument
3280 //
Richard Smith707eab62017-01-05 04:08:31 +00003281 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003282 if (!ILE->getNumInits())
3283 return Sema::TDK_Success;
3284
Richard Smitha7d5ec92017-01-04 19:47:19 +00003285 QualType ElTy;
3286 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3287 if (ArrTy)
3288 ElTy = ArrTy->getElementType();
3289 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3290 // Otherwise, an initializer list argument causes the parameter to be
3291 // considered a non-deduced context
3292 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003293 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003294
Faisal Valif6dfdb32015-12-10 05:36:39 +00003295 // Deduction only needs to be done for dependent types.
3296 if (ElTy->isDependentType()) {
3297 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003298 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smithc92d2062017-01-05 23:02:44 +00003299 S, TemplateParams, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3300 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003301 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003302 }
3303 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003304
3305 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3306 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003307 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003308 // Determine the array bound is something we can deduce.
3309 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003310 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003311 // We can perform template argument deduction for the given non-type
3312 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003313 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3314 ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003315 if (auto Result = DeduceNonTypeTemplateArgument(
3316 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3317 /*ArrayBound=*/true, Info, Deduced))
3318 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003319 }
3320 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003321
3322 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003323}
3324
Richard Smith707eab62017-01-05 04:08:31 +00003325/// \brief Perform template argument deduction per [temp.deduct.call] for a
3326/// single parameter / argument pair.
3327static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3328 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3329 Expr *Arg, TemplateDeductionInfo &Info,
3330 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3331 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003332 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003333 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003334 QualType OrigParamType = ParamType;
3335
3336 // If P is a reference type [...]
3337 // If P is a cv-qualified type [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003338 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith363ae812017-01-04 22:03:59 +00003339 ArgType, Arg, TDF))
3340 return Sema::TDK_Success;
3341
Richard Smith707eab62017-01-05 04:08:31 +00003342 // If [...] the argument is a non-empty initializer list [...]
3343 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3344 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003345 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003346
3347 // [...] the deduction process attempts to find template argument values
3348 // that will make the deduced A identical to A
3349 //
3350 // Keep track of the argument type and corresponding parameter index,
3351 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003352 OriginalCallArgs.push_back(
3353 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003355 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003356}
3357
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003358/// \brief Perform template argument deduction from a function call
3359/// (C++ [temp.deduct.call]).
3360///
3361/// \param FunctionTemplate the function template for which we are performing
3362/// template argument deduction.
3363///
James Dennett18348b62012-06-22 08:52:37 +00003364/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003365/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003366///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003367/// \param Args the function call arguments
3368///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003370/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003371/// template argument deduction.
3372///
3373/// \param Info the argument will be updated to provide additional information
3374/// about template argument deduction.
3375///
3376/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003377Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3378 FunctionTemplateDecl *FunctionTemplate,
3379 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003380 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Renato Golindad96d62017-01-02 11:15:42 +00003381 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003382 if (FunctionTemplate->isInvalidDecl())
3383 return TDK_Invalid;
3384
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003385 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003386 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003387
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003388 // C++ [temp.deduct.call]p1:
3389 // Template argument deduction is done by comparing each function template
3390 // parameter type (call it P) with the type of the corresponding argument
3391 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003392 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003393 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003394 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003395 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003396 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003397 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003398 if (Proto->isTemplateVariadic())
3399 /* Do nothing */;
3400 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003401 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003403 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Douglas Gregor89026b52009-06-30 23:57:56 +00003406 // The types of the parameters from which we will perform template argument
3407 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003408 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003409 TemplateParameterList *TemplateParams
3410 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<DeducedTemplateArgument, 4> Deduced;
3412 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003413 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003414 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003415 TemplateDeductionResult Result =
3416 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003417 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003418 Deduced,
3419 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003420 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003421 Info);
3422 if (Result)
3423 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003424
3425 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003426 } else {
3427 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003428 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003429 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3430 }
Mike Stump11289f42009-09-09 15:08:12 +00003431
Richard Smitha7d5ec92017-01-04 19:47:19 +00003432 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3433
3434 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3435 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003436 // C++ [demp.deduct.call]p1: (DR1391)
3437 // Template argument deduction is done by comparing each function template
3438 // parameter that contains template-parameters that participate in
3439 // template argument deduction ...
Richard Smitha7d5ec92017-01-04 19:47:19 +00003440 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3441 return Sema::TDK_Success;
3442
Richard Smith707eab62017-01-05 04:08:31 +00003443 // ... with the type of the corresponding argument
3444 return DeduceTemplateArgumentsFromCallArgument(
3445 *this, TemplateParams, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003446 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003447 };
3448
Douglas Gregor89026b52009-06-30 23:57:56 +00003449 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003450 Deduced.resize(TemplateParams->size());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003451 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003452 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003453 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003454
Richard Smitha7d5ec92017-01-04 19:47:19 +00003455 const PackExpansionType *ParamExpansion =
3456 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003457 if (!ParamExpansion) {
3458 // Simple case: matching a function parameter to a function argument.
3459 if (ArgIdx >= CheckArgs)
3460 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461
Richard Smitha7d5ec92017-01-04 19:47:19 +00003462 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003463 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003464
Douglas Gregor7825bf32011-01-06 22:09:01 +00003465 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor7825bf32011-01-06 22:09:01 +00003468 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469 // For a function parameter pack that occurs at the end of the
3470 // parameter-declaration-list, the type A of each remaining argument of
3471 // the call is compared with the type P of the declarator-id of the
3472 // function parameter pack. Each comparison deduces template arguments
3473 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003474 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003476 // the parameter pack is a non-deduced context.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003477 // FIXME: This does not say that subsequent parameters are also non-deduced.
3478 // See also DR1388 / DR1399, which effectively says we should keep deducing
3479 // after the pack.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003480 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003481 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
Douglas Gregor7825bf32011-01-06 22:09:01 +00003483 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003484 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3485 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486
Richard Smitha7d5ec92017-01-04 19:47:19 +00003487 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx)
3488 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3489 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregor7825bf32011-01-06 22:09:01 +00003491 // Build argument packs for each of the parameter packs expanded by this
3492 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003493 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003495
Douglas Gregor7825bf32011-01-06 22:09:01 +00003496 // After we've matching against a parameter pack, we're done.
3497 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003498 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003499
Mike Stump11289f42009-09-09 15:08:12 +00003500 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003501 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003502 Info, &OriginalCallArgs,
Renato Golindad96d62017-01-02 11:15:42 +00003503 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003504}
3505
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003506QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003507 QualType FunctionType,
3508 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003509 if (ArgFunctionType.isNull())
3510 return ArgFunctionType;
3511
3512 const FunctionProtoType *FunctionTypeP =
3513 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003514 const FunctionProtoType *ArgFunctionTypeP =
3515 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003516
3517 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3518 bool Rebuild = false;
3519
3520 CallingConv CC = FunctionTypeP->getCallConv();
3521 if (EPI.ExtInfo.getCC() != CC) {
3522 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3523 Rebuild = true;
3524 }
3525
3526 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3527 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3528 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3529 Rebuild = true;
3530 }
3531
3532 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3533 ArgFunctionTypeP->hasExceptionSpec())) {
3534 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3535 Rebuild = true;
3536 }
3537
3538 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003539 return ArgFunctionType;
3540
Richard Smithbaa47832016-12-01 02:11:49 +00003541 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3542 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003543}
3544
Douglas Gregor9b146582009-07-08 20:55:45 +00003545/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003546/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3547/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003548///
3549/// \param FunctionTemplate the function template for which we are performing
3550/// template argument deduction.
3551///
James Dennett18348b62012-06-22 08:52:37 +00003552/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003553/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003554///
3555/// \param ArgFunctionType the function type that will be used as the
3556/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003557/// function template's function type. This type may be NULL, if there is no
3558/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003559///
3560/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003561/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003562/// template argument deduction.
3563///
3564/// \param Info the argument will be updated to provide additional information
3565/// about template argument deduction.
3566///
Richard Smithbaa47832016-12-01 02:11:49 +00003567/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3568/// the address of a function template per [temp.deduct.funcaddr] and
3569/// [over.over]. If \c false, we are looking up a function template
3570/// specialization based on its signature, per [temp.deduct.decl].
3571///
Douglas Gregor9b146582009-07-08 20:55:45 +00003572/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003573Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3574 FunctionTemplateDecl *FunctionTemplate,
3575 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3576 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3577 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003578 if (FunctionTemplate->isInvalidDecl())
3579 return TDK_Invalid;
3580
Douglas Gregor9b146582009-07-08 20:55:45 +00003581 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3582 TemplateParameterList *TemplateParams
3583 = FunctionTemplate->getTemplateParameters();
3584 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003585
3586 // When taking the address of a function, we require convertibility of
3587 // the resulting function type. Otherwise, we allow arbitrary mismatches
3588 // of calling convention, noreturn, and noexcept.
3589 if (!IsAddressOfFunction)
3590 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3591 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003592
Douglas Gregor9b146582009-07-08 20:55:45 +00003593 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003594 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003595 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003596 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003597 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003598 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003599 if (TemplateDeductionResult Result
3600 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003601 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003602 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003603 &FunctionType, Info))
3604 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003605
3606 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003607 }
3608
Eli Friedman77dcc722012-02-08 03:07:05 +00003609 // Unevaluated SFINAE context.
3610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003611 SFINAETrap Trap(*this);
3612
John McCallc1f69982010-02-02 02:21:27 +00003613 Deduced.resize(TemplateParams->size());
3614
Richard Smith2a7d4812013-05-04 07:00:32 +00003615 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003616 // type so that we treat it as a non-deduced context in what follows. If we
3617 // are looking up by signature, the signature type should also have a deduced
3618 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003619 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003620 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003621 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003622 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003623 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003624 }
3625
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003626 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003627 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003628 if (IsAddressOfFunction)
3629 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003630 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003631 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003632 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003633 FunctionType, ArgFunctionType,
3634 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003635 return Result;
3636 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003639 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3640 NumExplicitlySpecified,
3641 Specialization, Info))
3642 return Result;
3643
Richard Smith2a7d4812013-05-04 07:00:32 +00003644 // If the function has a deduced return type, deduce it now, so we can check
3645 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003646 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003647 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003648 DeduceReturnType(Specialization, Info.getLocation(), false))
3649 return TDK_MiscellaneousDeductionFailure;
3650
Richard Smith9095e5b2016-11-01 01:31:23 +00003651 // If the function has a dependent exception specification, resolve it now,
3652 // so we can check that the exception specification matches.
3653 auto *SpecializationFPT =
3654 Specialization->getType()->castAs<FunctionProtoType>();
3655 if (getLangOpts().CPlusPlus1z &&
3656 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3657 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3658 return TDK_MiscellaneousDeductionFailure;
3659
Richard Smithbaa47832016-12-01 02:11:49 +00003660 // Adjust the exception specification of the argument again to match the
3661 // substituted and resolved type we just formed. (Calling convention and
3662 // noreturn can't be dependent, so we don't actually need this for them
3663 // right now.)
3664 QualType SpecializationType = Specialization->getType();
3665 if (!IsAddressOfFunction)
3666 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3667 /*AdjustExceptionSpec*/true);
3668
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003669 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003670 // specialization with respect to arguments of compatible pointer to function
3671 // types, template argument deduction fails.
3672 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003673 if (IsAddressOfFunction &&
3674 !isSameOrCompatibleFunctionType(
3675 Context.getCanonicalType(SpecializationType),
3676 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003677 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003678
3679 if (!IsAddressOfFunction &&
3680 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003681 return TDK_MiscellaneousDeductionFailure;
3682 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003683
3684 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003685}
3686
Simon Pilgrim728134c2016-08-12 11:43:57 +00003687/// \brief Given a function declaration (e.g. a generic lambda conversion
3688/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003689/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3690/// to replace 'auto' with and not the actual result type you want
3691/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003692static inline void
3693SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003694 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003695 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003696 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003697 assert(AutoResultType->getContainedAutoType());
3698 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003699 TypeToReplaceAutoWith);
3700 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3701}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003702
Simon Pilgrim728134c2016-08-12 11:43:57 +00003703/// \brief Given a specialized conversion operator of a generic lambda
3704/// create the corresponding specializations of the call operator and
3705/// the static-invoker. If the return type of the call operator is auto,
3706/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707/// return type of the destination function ptr.
3708
Simon Pilgrim728134c2016-08-12 11:43:57 +00003709static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003710SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3711 CXXConversionDecl *ConversionSpecialized,
3712 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3713 QualType ReturnTypeOfDestFunctionPtr,
3714 TemplateDeductionInfo &TDInfo,
3715 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003716
Faisal Vali2b3a3012013-10-24 23:40:02 +00003717 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003718 assert(LambdaClass && LambdaClass->isGenericLambda());
3719
Faisal Vali2b3a3012013-10-24 23:40:02 +00003720 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003721 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003722 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003723 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003724
3725 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 CallOpGeneric->getDescribedFunctionTemplate();
3727
Craig Topperc3ec1492014-05-26 06:22:03 +00003728 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003729 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003730 // generic lambda's call operator.
3731 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3733 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734 0, CallOpSpecialized, TDInfo))
3735 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003736
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003738 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3739 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003740 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003741 CallOpSpecialized->getPointOfInstantiation(),
3742 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003743
Faisal Vali2b3a3012013-10-24 23:40:02 +00003744 // Check to see if the return type of the destination ptr-to-function
3745 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003746 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003747 ReturnTypeOfDestFunctionPtr))
3748 return Sema::TDK_NonDeducedMismatch;
3749 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003750 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 // specialized our corresponding call operator, we are ready to
3752 // specialize the static invoker with the deduced arguments of our
3753 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003754 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3756 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3757
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003758#ifndef NDEBUG
3759 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3760#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003761 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003762 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003763 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003764 "If the call operator succeeded so should the invoker!");
3765 // Set the result type to match the corresponding call operator
3766 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003767 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3768 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003769 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003770 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003771 // to substitute into the 'auto' of the invoker and conversion
3772 // function.
3773 // For e.g.
3774 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3775 // We don't want to subst 'int*' into 'auto' to get int**.
3776
Alp Toker314cc812014-01-25 16:55:45 +00003777 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3778 ->getContainedAutoType()
3779 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003780 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3781 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003782 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003783 TypeToReplaceAutoWith, S);
3784 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003785
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003787 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003788 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003789 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003790 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3791 getType().getTypePtr()->castAs<FunctionProtoType>();
3792 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3793 EPI.TypeQuals = 0;
3794 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003795 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003796 return Sema::TDK_Success;
3797}
Douglas Gregor05155d82009-08-21 23:19:43 +00003798/// \brief Deduce template arguments for a templated conversion
3799/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3800/// conversion function template specialization.
3801Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003802Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003803 QualType ToType,
3804 CXXConversionDecl *&Specialization,
3805 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003806 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003807 return TDK_Invalid;
3808
Faisal Vali2b3a3012013-10-24 23:40:02 +00003809 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003810 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3811
Faisal Vali2b3a3012013-10-24 23:40:02 +00003812 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003813
3814 // Canonicalize the types for deduction.
3815 QualType P = Context.getCanonicalType(FromType);
3816 QualType A = Context.getCanonicalType(ToType);
3817
Douglas Gregord99609a2011-03-06 09:03:20 +00003818 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003819 // If P is a reference type, the type referred to by P is used for
3820 // type deduction.
3821 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3822 P = PRef->getPointeeType();
3823
Douglas Gregord99609a2011-03-06 09:03:20 +00003824 // C++0x [temp.deduct.conv]p4:
3825 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003826 // for type deduction.
3827 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003828 A = ARef->getPointeeType().getUnqualifiedType();
3829 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003830 //
Mike Stump11289f42009-09-09 15:08:12 +00003831 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003832 else {
3833 assert(!A->isReferenceType() && "Reference types were handled above");
3834
3835 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003836 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003837 // of P for type deduction; otherwise,
3838 if (P->isArrayType())
3839 P = Context.getArrayDecayedType(P);
3840 // - If P is a function type, the pointer type produced by the
3841 // function-to-pointer standard conversion (4.3) is used in
3842 // place of P for type deduction; otherwise,
3843 else if (P->isFunctionType())
3844 P = Context.getPointerType(P);
3845 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003846 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003847 else
3848 P = P.getUnqualifiedType();
3849
Douglas Gregord99609a2011-03-06 09:03:20 +00003850 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003851 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003852 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003853 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003854 A = A.getUnqualifiedType();
3855 }
3856
Eli Friedman77dcc722012-02-08 03:07:05 +00003857 // Unevaluated SFINAE context.
3858 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003859 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003860
3861 // C++ [temp.deduct.conv]p1:
3862 // Template argument deduction is done by comparing the return
3863 // type of the template conversion function (call it P) with the
3864 // type that is required as the result of the conversion (call it
3865 // A) as described in 14.8.2.4.
3866 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003867 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003868 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003869 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003870
3871 // C++0x [temp.deduct.conv]p4:
3872 // In general, the deduction process attempts to find template
3873 // argument values that will make the deduced A identical to
3874 // A. However, there are two cases that allow a difference:
3875 unsigned TDF = 0;
3876 // - If the original A is a reference type, A can be more
3877 // cv-qualified than the deduced A (i.e., the type referred to
3878 // by the reference)
3879 if (ToType->isReferenceType())
3880 TDF |= TDF_ParamWithReferenceType;
3881 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003882 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003883 // conversion.
3884 //
3885 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3886 // both P and A are pointers or member pointers. In this case, we
3887 // just ignore cv-qualifiers completely).
3888 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003889 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003890 TDF |= TDF_IgnoreQualifiers;
3891 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003892 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3893 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003894 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003895
3896 // Create an Instantiation Scope for finalizing the operator.
3897 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003898 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003899 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003900 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003901 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003902 ConversionSpecialized, Info);
3903 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3904
3905 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003906 // to a ptr-to-function, use the deduced arguments from the conversion
3907 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003908 // e.g., int (*fp)(int) = [](auto a) { return a; };
3909 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003910
Faisal Vali2b3a3012013-10-24 23:40:02 +00003911 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003912 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003913 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003914 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003915 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003916 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003917 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003918 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3919
Simon Pilgrim728134c2016-08-12 11:43:57 +00003920 // Create the corresponding specializations of the call operator and
3921 // the static-invoker; and if the return type is auto,
3922 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003923 // DestFunctionPtrReturnType.
3924 // For instance:
3925 // auto L = [](auto a) { return f(a); };
3926 // int (*fp)(int) = L;
3927 // char (*fp2)(int) = L; <-- Not OK.
3928
3929 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003930 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003931 Info, *this);
3932 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003933 return Result;
3934}
3935
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003936/// \brief Deduce template arguments for a function template when there is
3937/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3938///
3939/// \param FunctionTemplate the function template for which we are performing
3940/// template argument deduction.
3941///
James Dennett18348b62012-06-22 08:52:37 +00003942/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003943/// arguments.
3944///
3945/// \param Specialization if template argument deduction was successful,
3946/// this will be set to the function template specialization produced by
3947/// template argument deduction.
3948///
3949/// \param Info the argument will be updated to provide additional information
3950/// about template argument deduction.
3951///
Richard Smithbaa47832016-12-01 02:11:49 +00003952/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3953/// the address of a function template in a context where we do not have a
3954/// target type, per [over.over]. If \c false, we are looking up a function
3955/// template specialization based on its signature, which only happens when
3956/// deducing a function parameter type from an argument that is a template-id
3957/// naming a function template specialization.
3958///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003959/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003960Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3961 FunctionTemplateDecl *FunctionTemplate,
3962 TemplateArgumentListInfo *ExplicitTemplateArgs,
3963 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3964 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003965 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003966 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003967 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003968}
3969
Richard Smith30482bc2011-02-20 03:19:35 +00003970namespace {
3971 /// Substitute the 'auto' type specifier within a type for a given replacement
3972 /// type.
3973 class SubstituteAutoTransform :
3974 public TreeTransform<SubstituteAutoTransform> {
3975 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003976 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003977 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003978 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3979 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003980 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003981 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003982
Richard Smith30482bc2011-02-20 03:19:35 +00003983 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3984 // If we're building the type pattern to deduce against, don't wrap the
3985 // substituted type in an AutoType. Certain template deduction rules
3986 // apply only when a template type parameter appears directly (and not if
3987 // the parameter is found through desugaring). For instance:
3988 // auto &&lref = lvalue;
3989 // must transform into "rvalue reference to T" not "rvalue reference to
3990 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003991 if (!UseAutoSugar) {
3992 assert(isa<TemplateTypeParmType>(Replacement) &&
3993 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003994 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003995 TemplateTypeParmTypeLoc NewTL =
3996 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003997 NewTL.setNameLoc(TL.getNameLoc());
3998 return Result;
3999 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00004000 QualType Result = SemaRef.Context.getAutoType(
4001 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00004002 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4003 NewTL.setNameLoc(TL.getNameLoc());
4004 return Result;
4005 }
4006 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004007
4008 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4009 // Lambdas never need to be transformed.
4010 return E;
4011 }
Richard Smith061f1e22013-04-30 21:23:01 +00004012
Richard Smith2a7d4812013-05-04 07:00:32 +00004013 QualType Apply(TypeLoc TL) {
4014 // Create some scratch storage for the transformed type locations.
4015 // FIXME: We're just going to throw this information away. Don't build it.
4016 TypeLocBuilder TLB;
4017 TLB.reserve(TL.getFullDataSize());
4018 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004019 }
Richard Smith30482bc2011-02-20 03:19:35 +00004020 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004021}
Richard Smith30482bc2011-02-20 03:19:35 +00004022
Richard Smith2a7d4812013-05-04 07:00:32 +00004023Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004024Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4025 Optional<unsigned> DependentDeductionDepth) {
4026 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4027 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004028}
4029
Richard Smith061f1e22013-04-30 21:23:01 +00004030/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004031///
Richard Smith87d263e2016-12-25 08:05:23 +00004032/// Note that this is done even if the initializer is dependent. (This is
4033/// necessary to support partial ordering of templates using 'auto'.)
4034/// A dependent type will be produced when deducing from a dependent type.
4035///
Richard Smith30482bc2011-02-20 03:19:35 +00004036/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004037/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004038/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004039/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004040/// \param DependentDeductionDepth Set if we should permit deduction in
4041/// dependent cases. This is necessary for template partial ordering with
4042/// 'auto' template parameters. The value specified is the template
4043/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004044Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004045Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4046 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004047 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004048 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4049 if (NonPlaceholder.isInvalid())
4050 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004051 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004052 }
4053
Richard Smith87d263e2016-12-25 08:05:23 +00004054 if (!DependentDeductionDepth &&
4055 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4056 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004057 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004058 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004059 }
4060
Richard Smith87d263e2016-12-25 08:05:23 +00004061 // Find the depth of template parameter to synthesize.
4062 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4063
Richard Smith74aeef52013-04-26 16:15:35 +00004064 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4065 // Since 'decltype(auto)' can only occur at the top of the type, we
4066 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004067 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004068 if (AT->isDecltypeAuto()) {
4069 if (isa<InitListExpr>(Init)) {
4070 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4071 return DAR_FailedAlreadyDiagnosed;
4072 }
4073
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004074 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004075 if (Deduced.isNull())
4076 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004077 // FIXME: Support a non-canonical deduced type for 'auto'.
4078 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004079 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004080 if (Result.isNull())
4081 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004082 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004083 } else if (!getLangOpts().CPlusPlus) {
4084 if (isa<InitListExpr>(Init)) {
4085 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4086 return DAR_FailedAlreadyDiagnosed;
4087 }
Richard Smith74aeef52013-04-26 16:15:35 +00004088 }
4089 }
4090
Richard Smith30482bc2011-02-20 03:19:35 +00004091 SourceLocation Loc = Init->getExprLoc();
4092
4093 LocalInstantiationScope InstScope(*this);
4094
4095 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004096 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4097 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004098 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4099 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004100 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4101 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004102
Richard Smith87d263e2016-12-25 08:05:23 +00004103 QualType FuncParam =
4104 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4105 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004106 assert(!FuncParam.isNull() &&
4107 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004108
4109 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004110 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004111 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004112
Richard Smith87d263e2016-12-25 08:05:23 +00004113 TemplateDeductionInfo Info(Loc, Depth);
4114
4115 // If deduction failed, don't diagnose if the initializer is dependent; it
4116 // might acquire a matching type in the instantiation.
4117 auto DeductionFailed = [&]() -> DeduceAutoResult {
4118 if (Init->isTypeDependent()) {
4119 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4120 assert(!Result.isNull() && "substituting DependentTy can't fail");
4121 return DAR_Succeeded;
4122 }
4123 return DAR_Failed;
4124 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004125
Richard Smith707eab62017-01-05 04:08:31 +00004126 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4127
Richard Smith74801c82012-07-08 04:13:07 +00004128 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004129 if (InitList) {
4130 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004131 if (DeduceTemplateArgumentsFromCallArgument(
4132 *this, TemplateParamsSt.get(), TemplArg, InitList->getInit(i),
Richard Smithc92d2062017-01-05 23:02:44 +00004133 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4134 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004135 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004136 }
4137 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004138 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4139 Diag(Loc, diag::err_auto_bitfield);
4140 return DAR_FailedAlreadyDiagnosed;
4141 }
4142
Richard Smith707eab62017-01-05 04:08:31 +00004143 if (DeduceTemplateArgumentsFromCallArgument(
4144 *this, TemplateParamsSt.get(), FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004145 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004146 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004147 }
Richard Smith30482bc2011-02-20 03:19:35 +00004148
Richard Smith87d263e2016-12-25 08:05:23 +00004149 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004150 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004151 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004152
Eli Friedmane4310952012-11-06 23:56:42 +00004153 QualType DeducedType = Deduced[0].getAsType();
4154
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004155 if (InitList) {
4156 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4157 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004158 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004159 }
4160
Richard Smith061f1e22013-04-30 21:23:01 +00004161 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004162 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004163 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004164
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004165 // Check that the deduced argument type is compatible with the original
4166 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004167 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004168 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004169 assert((bool)InitList == OriginalArg.DecomposedParam &&
4170 "decomposed non-init-list in auto deduction?");
4171 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004172 Result = QualType();
4173 return DeductionFailed();
4174 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004175 }
4176
Sebastian Redl09edce02012-01-23 22:09:39 +00004177 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004178}
4179
Simon Pilgrim728134c2016-08-12 11:43:57 +00004180QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004181 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004182 if (TypeToReplaceAuto->isDependentType())
4183 TypeToReplaceAuto = QualType();
4184 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4185 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004186}
4187
Simon Pilgrim728134c2016-08-12 11:43:57 +00004188TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004189 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004190 if (TypeToReplaceAuto->isDependentType())
4191 TypeToReplaceAuto = QualType();
4192 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4193 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004194}
4195
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004196void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4197 if (isa<InitListExpr>(Init))
4198 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004199 VDecl->isInitCapture()
4200 ? diag::err_init_capture_deduction_failure_from_init_list
4201 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004202 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4203 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004204 Diag(VDecl->getLocation(),
4205 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4206 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004207 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4208 << Init->getSourceRange();
4209}
4210
Richard Smith2a7d4812013-05-04 07:00:32 +00004211bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4212 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004213 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004214
4215 if (FD->getTemplateInstantiationPattern())
4216 InstantiateFunctionDefinition(Loc, FD);
4217
Alp Toker314cc812014-01-25 16:55:45 +00004218 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004219 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4220 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4221 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4222 }
4223
4224 return StillUndeduced;
4225}
4226
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004227static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004228MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004229 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004230 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004231 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232
4233/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004234static void
4235AddImplicitObjectParameterType(ASTContext &Context,
4236 CXXMethodDecl *Method,
4237 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004238 // C++11 [temp.func.order]p3:
4239 // [...] The new parameter is of type "reference to cv A," where cv are
4240 // the cv-qualifiers of the function template (if any) and A is
4241 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004242 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004243 // The standard doesn't say explicitly, but we pick the appropriate kind of
4244 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004245 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4246 ArgTy = Context.getQualifiedType(ArgTy,
4247 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004248 if (Method->getRefQualifier() == RQ_RValue)
4249 ArgTy = Context.getRValueReferenceType(ArgTy);
4250 else
4251 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004252 ArgTypes.push_back(ArgTy);
4253}
4254
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004255/// \brief Determine whether the function template \p FT1 is at least as
4256/// specialized as \p FT2.
4257static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004258 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004259 FunctionTemplateDecl *FT1,
4260 FunctionTemplateDecl *FT2,
4261 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004262 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004263 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004265 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4266 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004268 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4269 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004270 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004271 Deduced.resize(TemplateParams->size());
4272
4273 // C++0x [temp.deduct.partial]p3:
4274 // The types used to determine the ordering depend on the context in which
4275 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004276 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004277 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 switch (TPOC) {
4279 case TPOC_Call: {
4280 // - In the context of a function call, the function parameter types are
4281 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004282 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4283 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004284
Eli Friedman3b5774a2012-09-19 23:27:04 +00004285 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004286 // [...] If only one of the function templates is a non-static
4287 // member, that function template is considered to have a new
4288 // first parameter inserted in its function parameter list. The
4289 // new parameter is of type "reference to cv A," where cv are
4290 // the cv-qualifiers of the function template (if any) and A is
4291 // the class of which the function template is a member.
4292 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004293 // Note that we interpret this to mean "if one of the function
4294 // templates is a non-static member and the other is a non-member";
4295 // otherwise, the ordering rules for static functions against non-static
4296 // functions don't make any sense.
4297 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004298 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4299 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004300 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004301
Richard Smithe5b52202013-09-11 00:52:39 +00004302 unsigned NumComparedArguments = NumCallArguments1;
4303
4304 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004305 // Compare 'this' from Method1 against first parameter from Method2.
4306 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4307 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004308 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004309 // Compare 'this' from Method2 against first parameter from Method1.
4310 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004311 }
4312
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004313 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004314 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004315 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004316 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregorb837ea42011-01-11 17:34:58 +00004318 // C++ [temp.func.order]p5:
4319 // The presence of unused ellipsis and default arguments has no effect on
4320 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004321 if (Args1.size() > NumComparedArguments)
4322 Args1.resize(NumComparedArguments);
4323 if (Args2.size() > NumComparedArguments)
4324 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004325 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4326 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004327 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004328 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004330 break;
4331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004333 case TPOC_Conversion:
4334 // - In the context of a call to a conversion operator, the return types
4335 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004336 if (DeduceTemplateArgumentsByTypeMatch(
4337 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4338 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004339 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004340 return false;
4341 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004343 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004344 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004345 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004346 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4347 FD2->getType(), FD1->getType(),
4348 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004349 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004350 return false;
4351 break;
4352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004354 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355 // In most cases, all template parameters must have values in order for
4356 // deduction to succeed, but for partial ordering purposes a template
4357 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // types being used for partial ordering. [ Note: a template parameter used
4359 // in a non-deduced context is considered used. -end note]
4360 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4361 for (; ArgIdx != NumArgs; ++ArgIdx)
4362 if (Deduced[ArgIdx].isNull())
4363 break;
4364
Richard Smithcf824862016-12-30 04:32:02 +00004365 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4366 // to substitute the deduced arguments back into the template and check that
4367 // we get the right type.
4368
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004369 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004371 // as FT2.
4372 return true;
4373 }
4374
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004375 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004376 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004377 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004378 case TPOC_Call:
4379 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4380 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004381 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004382 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004385 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004386 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4387 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004388 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004390 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004391 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004392 TemplateParams->getDepth(),
4393 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004394 break;
4395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004397 for (; ArgIdx != NumArgs; ++ArgIdx)
4398 // If this argument had no value deduced but was used in one of the types
4399 // used for partial ordering, then deduction fails.
4400 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4401 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004403 return true;
4404}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405
Douglas Gregorcef1a032011-01-16 16:03:23 +00004406/// \brief Determine whether this a function template whose parameter-type-list
4407/// ends with a function parameter pack.
4408static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4409 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4410 unsigned NumParams = Function->getNumParams();
4411 if (NumParams == 0)
4412 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregorcef1a032011-01-16 16:03:23 +00004414 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4415 if (!Last->isParameterPack())
4416 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregorcef1a032011-01-16 16:03:23 +00004418 // Make sure that no previous parameter is a parameter pack.
4419 while (--NumParams > 0) {
4420 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4421 return false;
4422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregorcef1a032011-01-16 16:03:23 +00004424 return true;
4425}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Douglas Gregorbe999392009-09-15 16:23:51 +00004427/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004428/// to the rules of function template partial ordering (C++ [temp.func.order]).
4429///
4430/// \param FT1 the first function template
4431///
4432/// \param FT2 the second function template
4433///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004434/// \param TPOC the context in which we are performing partial ordering of
4435/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004436///
Richard Smithe5b52202013-09-11 00:52:39 +00004437/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4438/// only when \c TPOC is \c TPOC_Call.
4439///
4440/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4441/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004442///
Douglas Gregorbe999392009-09-15 16:23:51 +00004443/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004444/// template is more specialized, returns NULL.
4445FunctionTemplateDecl *
4446Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4447 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004448 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004449 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004450 unsigned NumCallArguments1,
4451 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004453 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004455 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004457 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004458 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004460 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004461 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004462
Douglas Gregorcef1a032011-01-16 16:03:23 +00004463 // FIXME: This mimics what GCC implements, but doesn't match up with the
4464 // proposed resolution for core issue 692. This area needs to be sorted out,
4465 // but for now we attempt to maintain compatibility.
4466 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4467 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4468 if (Variadic1 != Variadic2)
4469 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Craig Topperc3ec1492014-05-26 06:22:03 +00004471 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004472}
Douglas Gregor9b146582009-07-08 20:55:45 +00004473
Douglas Gregor450f00842009-09-25 18:43:00 +00004474/// \brief Determine if the two templates are equivalent.
4475static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4476 if (T1 == T2)
4477 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 if (!T1 || !T2)
4480 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Douglas Gregor450f00842009-09-25 18:43:00 +00004482 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4483}
4484
4485/// \brief Retrieve the most specialized of the given function template
4486/// specializations.
4487///
John McCall58cc69d2010-01-27 01:50:18 +00004488/// \param SpecBegin the start iterator of the function template
4489/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004490///
John McCall58cc69d2010-01-27 01:50:18 +00004491/// \param SpecEnd the end iterator of the function template
4492/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004493///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004494/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004495/// diagnostic should occur.
4496///
4497/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4498/// no matching candidates.
4499///
4500/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4501/// occurs.
4502///
4503/// \param CandidateDiag partial diagnostic used for each function template
4504/// specialization that is a candidate in the ambiguous ordering. One parameter
4505/// in this diagnostic should be unbound, which will correspond to the string
4506/// describing the template arguments for the function template specialization.
4507///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004509/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004510UnresolvedSetIterator Sema::getMostSpecialized(
4511 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4512 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004513 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4514 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4515 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004516 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004517 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004518 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004519 FailedCandidates.NoteCandidates(*this, Loc);
4520 }
John McCall58cc69d2010-01-27 01:50:18 +00004521 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
4524 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004525 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
Douglas Gregor450f00842009-09-25 18:43:00 +00004527 // Find the function template that is better than all of the templates it
4528 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004529 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004531 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004533 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4534 FunctionTemplateDecl *Challenger
4535 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004536 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004537 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004538 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004539 Challenger)) {
4540 Best = I;
4541 BestTemplate = Challenger;
4542 }
4543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544
Douglas Gregor450f00842009-09-25 18:43:00 +00004545 // Make sure that the "best" function template is more specialized than all
4546 // of the others.
4547 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004548 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4549 FunctionTemplateDecl *Challenger
4550 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004551 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004553 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004554 BestTemplate)) {
4555 Ambiguous = true;
4556 break;
4557 }
4558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor450f00842009-09-25 18:43:00 +00004560 if (!Ambiguous) {
4561 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004562 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564
Douglas Gregor450f00842009-09-25 18:43:00 +00004565 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004566 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004567 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Richard Smithb875c432013-05-04 01:51:08 +00004569 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004570 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4571 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004572 const auto *FD = cast<FunctionDecl>(*I);
4573 PD << FD << getTemplateArgumentBindingsText(
4574 FD->getPrimaryTemplate()->getTemplateParameters(),
4575 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004576 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004577 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004578 Diag((*I)->getLocation(), PD);
4579 }
Richard Smithb875c432013-05-04 01:51:08 +00004580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581
John McCall58cc69d2010-01-27 01:50:18 +00004582 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004583}
4584
Richard Smith0da6dc42016-12-24 16:40:51 +00004585/// Determine whether one partial specialization, P1, is at least as
4586/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004587///
Richard Smith26b86ea2016-12-31 21:41:23 +00004588/// \tparam TemplateLikeDecl The kind of P2, which must be a
4589/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004590/// \param T1 The injected-class-name of P1 (faked for a variable template).
4591/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004592template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004593static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004594 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004595 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004596 // C++ [temp.class.order]p1:
4597 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 // specialized as the second if, given the following rewrite to two
4599 // function templates, the first function template is at least as
4600 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004601 // templates (14.6.6.2):
4602 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603 // first partial specialization and has a single function parameter
4604 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004605 // arguments of the first partial specialization, and
4606 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607 // second partial specialization and has a single function parameter
4608 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004609 // arguments of the second partial specialization.
4610 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004611 // Rather than synthesize function templates, we merely perform the
4612 // equivalent partial ordering by performing deduction directly on
4613 // the template arguments of the class template partial
4614 // specializations. This computation is slightly simpler than the
4615 // general problem of function template partial ordering, because
4616 // class template partial specializations are more constrained. We
4617 // know that every template parameter is deducible from the class
4618 // template partial specialization's template arguments, for
4619 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004620 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004621
Richard Smith0da6dc42016-12-24 16:40:51 +00004622 // Determine whether P1 is at least as specialized as P2.
4623 Deduced.resize(P2->getTemplateParameters()->size());
4624 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4625 T2, T1, Info, Deduced, TDF_None,
4626 /*PartialOrdering=*/true))
4627 return false;
4628
4629 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4630 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004631 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4632 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004633 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4634 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004635 S, P2, /*PartialOrdering=*/true,
4636 TemplateArgumentList(TemplateArgumentList::OnStack,
4637 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004638 Deduced, Info))
4639 return false;
4640
4641 return true;
4642}
4643
4644/// \brief Returns the more specialized class template partial specialization
4645/// according to the rules of partial ordering of class template partial
4646/// specializations (C++ [temp.class.order]).
4647///
4648/// \param PS1 the first class template partial specialization
4649///
4650/// \param PS2 the second class template partial specialization
4651///
4652/// \returns the more specialized class template partial specialization. If
4653/// neither partial specialization is more specialized, returns NULL.
4654ClassTemplatePartialSpecializationDecl *
4655Sema::getMoreSpecializedPartialSpecialization(
4656 ClassTemplatePartialSpecializationDecl *PS1,
4657 ClassTemplatePartialSpecializationDecl *PS2,
4658 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004659 QualType PT1 = PS1->getInjectedSpecializationType();
4660 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Richard Smith0e617ec2016-12-27 07:56:27 +00004662 TemplateDeductionInfo Info(Loc);
4663 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4664 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004665
4666 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004667 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004668
4669 return Better1 ? PS1 : PS2;
4670}
4671
Richard Smith0e617ec2016-12-27 07:56:27 +00004672bool Sema::isMoreSpecializedThanPrimary(
4673 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4674 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4675 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4676 QualType PartialT = Spec->getInjectedSpecializationType();
4677 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4678 return false;
4679 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4680 Info.clearSFINAEDiagnostic();
4681 return false;
4682 }
4683 return true;
4684}
4685
Larisse Voufo39a1e502013-08-06 01:03:05 +00004686VarTemplatePartialSpecializationDecl *
4687Sema::getMoreSpecializedPartialSpecialization(
4688 VarTemplatePartialSpecializationDecl *PS1,
4689 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004690 // Pretend the variable template specializations are class template
4691 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004692 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004693 "the partial specializations being compared should specialize"
4694 " the same template.");
4695 TemplateName Name(PS1->getSpecializedTemplate());
4696 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4697 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004698 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004699 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004700 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004701
Richard Smith0e617ec2016-12-27 07:56:27 +00004702 TemplateDeductionInfo Info(Loc);
4703 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4704 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Douglas Gregorbe999392009-09-15 16:23:51 +00004706 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004707 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Richard Smith0da6dc42016-12-24 16:40:51 +00004709 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004710}
4711
Richard Smith0e617ec2016-12-27 07:56:27 +00004712bool Sema::isMoreSpecializedThanPrimary(
4713 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4714 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4715 // FIXME: Cache the injected template arguments rather than recomputing
4716 // them for each partial specialization.
4717 SmallVector<TemplateArgument, 8> PrimaryArgs;
4718 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4719 PrimaryArgs);
4720
4721 TemplateName CanonTemplate =
4722 Context.getCanonicalTemplateName(TemplateName(Primary));
4723 QualType PrimaryT = Context.getTemplateSpecializationType(
4724 CanonTemplate, PrimaryArgs);
4725 QualType PartialT = Context.getTemplateSpecializationType(
4726 CanonTemplate, Spec->getTemplateArgs().asArray());
4727 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4728 return false;
4729 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4730 Info.clearSFINAEDiagnostic();
4731 return false;
4732 }
4733 return true;
4734}
4735
Richard Smith26b86ea2016-12-31 21:41:23 +00004736bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4737 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4738 // C++1z [temp.arg.template]p4: (DR 150)
4739 // A template template-parameter P is at least as specialized as a
4740 // template template-argument A if, given the following rewrite to two
4741 // function templates...
4742
4743 // Rather than synthesize function templates, we merely perform the
4744 // equivalent partial ordering by performing deduction directly on
4745 // the template parameter lists of the template template parameters.
4746 //
4747 // Given an invented class template X with the template parameter list of
4748 // A (including default arguments):
4749 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4750 TemplateParameterList *A = AArg->getTemplateParameters();
4751
4752 // - Each function template has a single function parameter whose type is
4753 // a specialization of X with template arguments corresponding to the
4754 // template parameters from the respective function template
4755 SmallVector<TemplateArgument, 8> AArgs;
4756 Context.getInjectedTemplateArgs(A, AArgs);
4757
4758 // Check P's arguments against A's parameter list. This will fill in default
4759 // template arguments as needed. AArgs are already correct by construction.
4760 // We can't just use CheckTemplateIdType because that will expand alias
4761 // templates.
4762 SmallVector<TemplateArgument, 4> PArgs;
4763 {
4764 SFINAETrap Trap(*this);
4765
4766 Context.getInjectedTemplateArgs(P, PArgs);
4767 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4768 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4769 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4770 // expansions, to form an "as written" argument list.
4771 TemplateArgument Arg = PArgs[I];
4772 if (Arg.getKind() == TemplateArgument::Pack) {
4773 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4774 Arg = *Arg.pack_begin();
4775 }
4776 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4777 Arg, QualType(), P->getParam(I)->getLocation()));
4778 }
4779 PArgs.clear();
4780
4781 // C++1z [temp.arg.template]p3:
4782 // If the rewrite produces an invalid type, then P is not at least as
4783 // specialized as A.
4784 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4785 Trap.hasErrorOccurred())
4786 return false;
4787 }
4788
4789 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4790 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4791
Richard Smith26b86ea2016-12-31 21:41:23 +00004792 // ... the function template corresponding to P is at least as specialized
4793 // as the function template corresponding to A according to the partial
4794 // ordering rules for function templates.
4795 TemplateDeductionInfo Info(Loc, A->getDepth());
4796 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4797}
4798
Mike Stump11289f42009-09-09 15:08:12 +00004799static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004800MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004801 const TemplateArgument &TemplateArg,
4802 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004803 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004804 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004805
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004807/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004808static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004809MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004810 const Expr *E,
4811 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004812 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004813 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004814 // We can deduce from a pack expansion.
4815 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4816 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Richard Smith34349002012-07-09 03:07:20 +00004818 // Skip through any implicit casts we added while type-checking, and any
4819 // substitutions performed by template alias expansion.
4820 while (1) {
4821 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4822 E = ICE->getSubExpr();
4823 else if (const SubstNonTypeTemplateParmExpr *Subst =
4824 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4825 E = Subst->getReplacement();
4826 else
4827 break;
4828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
4830 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004831 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004832 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004833 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004834 return;
4835
Mike Stump11289f42009-09-09 15:08:12 +00004836 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004837 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4838 if (!NTTP)
4839 return;
4840
Douglas Gregor21610382009-10-29 00:04:11 +00004841 if (NTTP->getDepth() == Depth)
4842 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004843
4844 // In C++1z mode, additional arguments may be deduced from the type of a
4845 // non-type argument.
4846 if (Ctx.getLangOpts().CPlusPlus1z)
4847 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004848}
4849
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004850/// \brief Mark the template parameters that are used by the given
4851/// nested name specifier.
4852static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004853MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004854 NestedNameSpecifier *NNS,
4855 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004856 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004857 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004858 if (!NNS)
4859 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004860
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004861 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004862 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004863 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004864 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004865}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004867/// \brief Mark the template parameters that are used by the given
4868/// template name.
4869static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004870MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 TemplateName Name,
4872 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004873 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004874 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004875 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4876 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004877 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4878 if (TTP->getDepth() == Depth)
4879 Used[TTP->getIndex()] = true;
4880 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004881 return;
4882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004884 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004885 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004886 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004887 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004888 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004889 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004890}
4891
4892/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004893/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004894static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004895MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004896 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004897 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004898 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004899 if (T.isNull())
4900 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Douglas Gregor91772d12009-06-13 00:26:55 +00004902 // Non-dependent types have nothing deducible
4903 if (!T->isDependentType())
4904 return;
4905
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004906 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004907 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004908 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004909 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004910 cast<PointerType>(T)->getPointeeType(),
4911 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004912 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004913 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004914 break;
4915
4916 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004917 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004918 cast<BlockPointerType>(T)->getPointeeType(),
4919 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004920 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004921 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004922 break;
4923
4924 case Type::LValueReference:
4925 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004926 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004927 cast<ReferenceType>(T)->getPointeeType(),
4928 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004929 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004930 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004931 break;
4932
4933 case Type::MemberPointer: {
4934 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004936 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004937 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004938 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004939 break;
4940 }
4941
4942 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004943 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004944 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004945 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004946 // Fall through to check the element type
4947
4948 case Type::ConstantArray:
4949 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004950 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004951 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004952 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004953 break;
4954
4955 case Type::Vector:
4956 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004957 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004958 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004959 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004960 break;
4961
Douglas Gregor758a8692009-06-17 21:51:59 +00004962 case Type::DependentSizedExtVector: {
4963 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004964 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004965 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004966 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004967 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004968 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004969 break;
4970 }
4971
Douglas Gregor91772d12009-06-13 00:26:55 +00004972 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004973 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004974 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4975 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004976 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4977 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004978 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004979 break;
4980 }
4981
Douglas Gregor21610382009-10-29 00:04:11 +00004982 case Type::TemplateTypeParm: {
4983 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4984 if (TTP->getDepth() == Depth)
4985 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004986 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004987 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004988
Douglas Gregorfb322d82011-01-14 05:11:40 +00004989 case Type::SubstTemplateTypeParmPack: {
4990 const SubstTemplateTypeParmPackType *Subst
4991 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004992 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004993 QualType(Subst->getReplacedParameter(), 0),
4994 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004995 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004996 OnlyDeduced, Depth, Used);
4997 break;
4998 }
4999
John McCall2408e322010-04-27 00:57:59 +00005000 case Type::InjectedClassName:
5001 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5002 // fall through
5003
Douglas Gregor91772d12009-06-13 00:26:55 +00005004 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005005 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005006 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005007 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005008 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregord0ad2942010-12-23 01:24:45 +00005010 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005011 // If the template argument list of P contains a pack expansion that is
5012 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005013 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005015 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005016 break;
5017
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005018 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005019 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005020 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005021 break;
5022 }
5023
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005024 case Type::Complex:
5025 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005026 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005027 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005028 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005029 break;
5030
Eli Friedman0dfb8892011-10-06 23:00:33 +00005031 case Type::Atomic:
5032 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005034 cast<AtomicType>(T)->getValueType(),
5035 OnlyDeduced, Depth, Used);
5036 break;
5037
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005038 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005039 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005040 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005041 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005042 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005043 break;
5044
John McCallc392f372010-06-11 00:33:02 +00005045 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005046 // C++14 [temp.deduct.type]p5:
5047 // The non-deduced contexts are:
5048 // -- The nested-name-specifier of a type that was specified using a
5049 // qualified-id
5050 //
5051 // C++14 [temp.deduct.type]p6:
5052 // When a type name is specified in a way that includes a non-deduced
5053 // context, all of the types that comprise that type name are also
5054 // non-deduced.
5055 if (OnlyDeduced)
5056 break;
5057
John McCallc392f372010-06-11 00:33:02 +00005058 const DependentTemplateSpecializationType *Spec
5059 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060
Richard Smith50d5b972015-12-30 20:56:05 +00005061 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5062 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005063
John McCallc392f372010-06-11 00:33:02 +00005064 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005065 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005066 Used);
5067 break;
5068 }
5069
John McCallbd8d9bd2010-03-01 23:49:17 +00005070 case Type::TypeOf:
5071 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005072 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005073 cast<TypeOfType>(T)->getUnderlyingType(),
5074 OnlyDeduced, Depth, Used);
5075 break;
5076
5077 case Type::TypeOfExpr:
5078 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005079 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005080 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5081 OnlyDeduced, Depth, Used);
5082 break;
5083
5084 case Type::Decltype:
5085 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005086 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005087 cast<DecltypeType>(T)->getUnderlyingExpr(),
5088 OnlyDeduced, Depth, Used);
5089 break;
5090
Alexis Hunte852b102011-05-24 22:41:36 +00005091 case Type::UnaryTransform:
5092 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005093 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005094 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005095 OnlyDeduced, Depth, Used);
5096 break;
5097
Douglas Gregord2fa7662010-12-20 02:24:11 +00005098 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005099 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005100 cast<PackExpansionType>(T)->getPattern(),
5101 OnlyDeduced, Depth, Used);
5102 break;
5103
Richard Smith30482bc2011-02-20 03:19:35 +00005104 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005105 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005106 cast<AutoType>(T)->getDeducedType(),
5107 OnlyDeduced, Depth, Used);
5108
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005109 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005110 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005111 case Type::VariableArray:
5112 case Type::FunctionNoProto:
5113 case Type::Record:
5114 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005115 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005116 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005117 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005118 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005119 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005120#define TYPE(Class, Base)
5121#define ABSTRACT_TYPE(Class, Base)
5122#define DEPENDENT_TYPE(Class, Base)
5123#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5124#include "clang/AST/TypeNodes.def"
5125 break;
5126 }
5127}
5128
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005129/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005130/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005131static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005132MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005133 const TemplateArgument &TemplateArg,
5134 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005135 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005136 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005137 switch (TemplateArg.getKind()) {
5138 case TemplateArgument::Null:
5139 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005140 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005141 break;
Mike Stump11289f42009-09-09 15:08:12 +00005142
Eli Friedmanb826a002012-09-26 02:36:12 +00005143 case TemplateArgument::NullPtr:
5144 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5145 Depth, Used);
5146 break;
5147
Douglas Gregor91772d12009-06-13 00:26:55 +00005148 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005149 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005150 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005151 break;
5152
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005153 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005154 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005155 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005157 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005158 break;
5159
5160 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005161 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005162 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005163 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005164
Anders Carlssonbc343912009-06-15 17:04:53 +00005165 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005166 for (const auto &P : TemplateArg.pack_elements())
5167 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005168 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005169 }
5170}
5171
James Dennett41725122012-06-22 10:16:05 +00005172/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005173/// template argument list.
5174///
5175/// \param TemplateArgs the template argument list from which template
5176/// parameters will be deduced.
5177///
James Dennett41725122012-06-22 10:16:05 +00005178/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005179/// to indicate when the corresponding template parameter will be
5180/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005181void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005182Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005183 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005184 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005185 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186 // If the template argument list of P contains a pack expansion that is not
5187 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005188 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005190 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005191 return;
5192
Douglas Gregor91772d12009-06-13 00:26:55 +00005193 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005194 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005195 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005196}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005197
5198/// \brief Marks all of the template parameters that will be deduced by a
5199/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005200void Sema::MarkDeducedTemplateParameters(
5201 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5202 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005204 = FunctionTemplate->getTemplateParameters();
5205 Deduced.clear();
5206 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207
Douglas Gregorce23bae2009-09-18 23:21:38 +00005208 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5209 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005210 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005211 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005212}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005213
5214bool hasDeducibleTemplateParameters(Sema &S,
5215 FunctionTemplateDecl *FunctionTemplate,
5216 QualType T) {
5217 if (!T->isDependentType())
5218 return false;
5219
5220 TemplateParameterList *TemplateParams
5221 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005222 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005223 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005224 Deduced);
5225
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005226 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005227}