blob: 3197647d8d8beb3f1326e20a88df161eef5e143f [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 Smithde0d34a2017-01-09 07:14:40 +0000672 /// Determine whether this pack has already been partially expanded into a
673 /// sequence of (prior) function parameters / template arguments.
674 bool isPartiallyExpanded() {
675 if (Packs.size() != 1 || !S.CurrentInstantiationScope)
676 return false;
677
678 auto *PartiallySubstitutedPack =
679 S.CurrentInstantiationScope->getPartiallySubstitutedPack();
680 return PartiallySubstitutedPack &&
681 getDepthAndIndex(PartiallySubstitutedPack) ==
682 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
683 }
684
Richard Smith0a80d572014-05-29 01:12:14 +0000685 /// Move to deducing the next element in each pack that is being deduced.
686 void nextPackElement() {
687 // Capture the deduced template arguments for each parameter pack expanded
688 // by this pack expansion, add them to the list of arguments we've deduced
689 // for that pack, then clear out the deduced argument.
690 for (auto &Pack : Packs) {
691 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000692 if (!Pack.New.empty() || !DeducedArg.isNull()) {
693 while (Pack.New.size() < PackElements)
694 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith0a80d572014-05-29 01:12:14 +0000695 Pack.New.push_back(DeducedArg);
696 DeducedArg = DeducedTemplateArgument();
697 }
698 }
Richard Smith539e8e32017-01-04 01:48:55 +0000699 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000700 }
701
702 /// \brief Finish template argument deduction for a set of argument packs,
703 /// producing the argument packs and checking for consistency with prior
704 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000705 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000706 // Build argument packs for each of the parameter packs expanded by this
707 // pack expansion.
708 for (auto &Pack : Packs) {
709 // Put back the old value for this pack.
710 Deduced[Pack.Index] = Pack.Saved;
711
712 // Build or find a new value for this pack.
713 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000714 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000715 if (Pack.DeferredDeduction.isNull()) {
716 // We were not able to deduce anything for this parameter pack
717 // (because it only appeared in non-deduced contexts), so just
718 // restore the saved argument pack.
719 continue;
720 }
721
722 NewPack = Pack.DeferredDeduction;
723 Pack.DeferredDeduction = TemplateArgument();
724 } else if (Pack.New.empty()) {
725 // If we deduced an empty argument pack, create it now.
726 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
727 } else {
728 TemplateArgument *ArgumentPack =
729 new (S.Context) TemplateArgument[Pack.New.size()];
730 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
731 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000732 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000733 Pack.New[0].wasDeducedFromArrayBound());
734 }
735
736 // Pick where we're going to put the merged pack.
737 DeducedTemplateArgument *Loc;
738 if (Pack.Outer) {
739 if (Pack.Outer->DeferredDeduction.isNull()) {
740 // Defer checking this pack until we have a complete pack to compare
741 // it against.
742 Pack.Outer->DeferredDeduction = NewPack;
743 continue;
744 }
745 Loc = &Pack.Outer->DeferredDeduction;
746 } else {
747 Loc = &Deduced[Pack.Index];
748 }
749
750 // Check the new pack matches any previous value.
751 DeducedTemplateArgument OldPack = *Loc;
752 DeducedTemplateArgument Result =
753 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
754
755 // If we deferred a deduction of this pack, check that one now too.
756 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
757 OldPack = Result;
758 NewPack = Pack.DeferredDeduction;
759 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
760 }
761
762 if (Result.isNull()) {
763 Info.Param =
764 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
765 Info.FirstArg = OldPack;
766 Info.SecondArg = NewPack;
767 return Sema::TDK_Inconsistent;
768 }
769
770 *Loc = Result;
771 }
772
773 return Sema::TDK_Success;
774 }
775
776private:
777 Sema &S;
778 TemplateParameterList *TemplateParams;
779 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
780 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000781 unsigned PackElements = 0;
Richard Smith0a80d572014-05-29 01:12:14 +0000782
783 SmallVector<DeducedPack, 2> Packs;
784};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000785} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000786
Douglas Gregor5499af42011-01-05 23:12:31 +0000787/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788/// types to the list of argument types, as in the parameter-type-lists of
789/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000790///
791/// \param S The semantic analysis object within which we are deducing
792///
793/// \param TemplateParams The template parameters that we are deducing
794///
795/// \param Params The list of parameter types
796///
797/// \param NumParams The number of types in \c Params
798///
799/// \param Args The list of argument types
800///
801/// \param NumArgs The number of types in \c Args
802///
803/// \param Info information about the template argument deduction itself
804///
805/// \param Deduced the deduced template arguments
806///
807/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
808/// how template argument deduction is performed.
809///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000810/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000812/// (C++0x [temp.deduct.partial]).
813///
Douglas Gregor5499af42011-01-05 23:12:31 +0000814/// \returns the result of template argument deduction so far. Note that a
815/// "success" result means that template argument deduction has not yet failed,
816/// but it may still fail, later, for other reasons.
817static Sema::TemplateDeductionResult
818DeduceTemplateArguments(Sema &S,
819 TemplateParameterList *TemplateParams,
820 const QualType *Params, unsigned NumParams,
821 const QualType *Args, unsigned NumArgs,
822 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000823 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000824 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000825 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000826 // Fast-path check to see if we have too many/too few arguments.
827 if (NumParams != NumArgs &&
828 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
829 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000830 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
Douglas Gregor5499af42011-01-05 23:12:31 +0000832 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833 // Similarly, if P has a form that contains (T), then each parameter type
834 // Pi of the respective parameter-type- list of P is compared with the
835 // corresponding parameter type Ai of the corresponding parameter-type-list
836 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000837 unsigned ArgIdx = 0, ParamIdx = 0;
838 for (; ParamIdx != NumParams; ++ParamIdx) {
839 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000840 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
842 if (!Expansion) {
843 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor5499af42011-01-05 23:12:31 +0000845 // Make sure we have an argument.
846 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000847 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000849 if (isa<PackExpansionType>(Args[ArgIdx])) {
850 // C++0x [temp.deduct.type]p22:
851 // If the original function parameter associated with A is a function
852 // parameter pack and the function parameter associated with P is not
853 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000854 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856
Douglas Gregor5499af42011-01-05 23:12:31 +0000857 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000858 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
859 Params[ParamIdx], Args[ArgIdx],
860 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000861 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 ++ArgIdx;
865 continue;
866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000868 // C++0x [temp.deduct.type]p5:
869 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000871 // parameter-declaration-clause.
872 if (ParamIdx + 1 < NumParams)
873 return Sema::TDK_Success;
874
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000879 // comparison deduces template arguments for subsequent positions in the
880 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000883 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Douglas Gregor5499af42011-01-05 23:12:31 +0000885 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000888 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
889 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000890 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000891 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Richard Smith0a80d572014-05-29 01:12:14 +0000893 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895
Douglas Gregor5499af42011-01-05 23:12:31 +0000896 // Build argument packs for each of the parameter packs expanded by this
897 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000898 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Douglas Gregor5499af42011-01-05 23:12:31 +0000902 // Make sure we don't have any extra arguments.
903 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000904 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905
Douglas Gregor5499af42011-01-05 23:12:31 +0000906 return Sema::TDK_Success;
907}
908
Douglas Gregor1d684c22011-04-28 00:56:09 +0000909/// \brief Determine whether the parameter has qualifiers that are either
910/// inconsistent with or a superset of the argument's qualifiers.
911static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
912 QualType ArgType) {
913 Qualifiers ParamQs = ParamType.getQualifiers();
914 Qualifiers ArgQs = ArgType.getQualifiers();
915
916 if (ParamQs == ArgQs)
917 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000918
Douglas Gregor1d684c22011-04-28 00:56:09 +0000919 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000920 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000921 ParamQs.hasObjCGCAttr())
922 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000923
Douglas Gregor1d684c22011-04-28 00:56:09 +0000924 // Mismatched (but not missing) address spaces.
925 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
926 ParamQs.hasAddressSpace())
927 return true;
928
John McCall31168b02011-06-15 23:02:42 +0000929 // Mismatched (but not missing) Objective-C lifetime qualifiers.
930 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
931 ParamQs.hasObjCLifetime())
932 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000933
Douglas Gregor1d684c22011-04-28 00:56:09 +0000934 // CVR qualifier superset.
935 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
936 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
937 == ParamQs.getCVRQualifiers());
938}
939
Douglas Gregor19a41f12013-04-17 08:45:07 +0000940/// \brief Compare types for equality with respect to possibly compatible
941/// function types (noreturn adjustment, implicit calling conventions). If any
942/// of parameter and argument is not a function, just perform type comparison.
943///
944/// \param Param the template parameter type.
945///
946/// \param Arg the argument type.
947bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
948 CanQualType Arg) {
949 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
950 *ArgFunction = Arg->getAs<FunctionType>();
951
952 // Just compare if not functions.
953 if (!ParamFunction || !ArgFunction)
954 return Param == Arg;
955
Richard Smith3c4f8d22016-10-16 17:54:23 +0000956 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000957 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000958 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000959 return Arg == Context.getCanonicalType(AdjustedParam);
960
961 // FIXME: Compatible calling conventions.
962
963 return Param == Arg;
964}
965
Douglas Gregorcceb9752009-06-26 18:27:22 +0000966/// \brief Deduce the template arguments by comparing the parameter type and
967/// the argument type (C++ [temp.deduct.type]).
968///
Chandler Carruthc1263112010-02-07 21:33:28 +0000969/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000970///
971/// \param TemplateParams the template parameters that we are deducing
972///
973/// \param ParamIn the parameter type
974///
975/// \param ArgIn the argument type
976///
977/// \param Info information about the template argument deduction itself
978///
979/// \param Deduced the deduced template arguments
980///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000981/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000982/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000983///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000984/// \param PartialOrdering Whether we're performing template argument deduction
985/// in the context of partial ordering (C++0x [temp.deduct.partial]).
986///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000987/// \returns the result of template argument deduction so far. Note that a
988/// "success" result means that template argument deduction has not yet failed,
989/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000990static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000991DeduceTemplateArgumentsByTypeMatch(Sema &S,
992 TemplateParameterList *TemplateParams,
993 QualType ParamIn, QualType ArgIn,
994 TemplateDeductionInfo &Info,
995 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
996 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000997 bool PartialOrdering,
998 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000999 // We only want to look at the canonical types, since typedefs and
1000 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001001 QualType Param = S.Context.getCanonicalType(ParamIn);
1002 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001003
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001004 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001006 if (const PackExpansionType *ArgExpansion
1007 = dyn_cast<PackExpansionType>(Arg))
1008 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Douglas Gregorb837ea42011-01-11 17:34:58 +00001010 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001011 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // Before the partial ordering is done, certain transformations are
1013 // performed on the types used for partial ordering:
1014 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001015 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1016 if (ParamRef)
1017 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001018
Douglas Gregorb837ea42011-01-11 17:34:58 +00001019 // - If A is a reference type, A is replaced by the type referred to.
1020 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1021 if (ArgRef)
1022 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023
Richard Smithed563c22015-02-20 04:45:22 +00001024 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1025 // C++11 [temp.deduct.partial]p9:
1026 // If, for a given type, deduction succeeds in both directions (i.e.,
1027 // the types are identical after the transformations above) and both
1028 // P and A were reference types [...]:
1029 // - if [one type] was an lvalue reference and [the other type] was
1030 // not, [the other type] is not considered to be at least as
1031 // specialized as [the first type]
1032 // - if [one type] is more cv-qualified than [the other type],
1033 // [the other type] is not considered to be at least as specialized
1034 // as [the first type]
1035 // Objective-C ARC adds:
1036 // - [one type] has non-trivial lifetime, [the other type] has
1037 // __unsafe_unretained lifetime, and the types are otherwise
1038 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001039 //
Richard Smithed563c22015-02-20 04:45:22 +00001040 // A is "considered to be at least as specialized" as P iff deduction
1041 // succeeds, so we model this as a deduction failure. Note that
1042 // [the first type] is P and [the other type] is A here; the standard
1043 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001044 Qualifiers ParamQuals = Param.getQualifiers();
1045 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001046 if ((ParamRef->isLValueReferenceType() &&
1047 !ArgRef->isLValueReferenceType()) ||
1048 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1049 (ParamQuals.hasNonTrivialObjCLifetime() &&
1050 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1051 ParamQuals.withoutObjCLifetime() ==
1052 ArgQuals.withoutObjCLifetime())) {
1053 Info.FirstArg = TemplateArgument(ParamIn);
1054 Info.SecondArg = TemplateArgument(ArgIn);
1055 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001056 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058
Richard Smithed563c22015-02-20 04:45:22 +00001059 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001060 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001062 // version of P.
1063 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001065 // version of A.
1066 Arg = Arg.getUnqualifiedType();
1067 } else {
1068 // C++0x [temp.deduct.call]p4 bullet 1:
1069 // - If the original P is a reference type, the deduced A (i.e., the type
1070 // referred to by the reference) can be more cv-qualified than the
1071 // transformed A.
1072 if (TDF & TDF_ParamWithReferenceType) {
1073 Qualifiers Quals;
1074 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1075 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001076 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001077 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Douglas Gregor85f240c2011-01-25 17:19:08 +00001080 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1081 // C++0x [temp.deduct.type]p10:
1082 // If P and A are function types that originated from deduction when
1083 // taking the address of a function template (14.8.2.2) or when deducing
1084 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085 // Ai are parameters of the top-level parameter-type-list of P and A,
1086 // respectively, Pi is adjusted if it is an rvalue reference to a
1087 // cv-unqualified template parameter and Ai is an lvalue reference, in
1088 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001089 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1090 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001091 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001092 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
Douglas Gregor85f240c2011-01-25 17:19:08 +00001094 if (const RValueReferenceType *ParamRef
1095 = Param->getAs<RValueReferenceType>()) {
1096 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1097 !ParamRef->getPointeeType().getQualifiers())
1098 if (Arg->isLValueReferenceType())
1099 Param = ParamRef->getPointeeType();
1100 }
1101 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001104 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001105 // A template type argument T, a template template argument TT or a
1106 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001107 // the following forms:
1108 //
1109 // T
1110 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001111 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001112 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001113 // Just skip any attempts to deduce from a placeholder type or a parameter
1114 // at a different depth.
1115 if (Arg->isPlaceholderType() ||
1116 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001117 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001118
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001119 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001120 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Douglas Gregor60454822009-07-22 20:02:25 +00001122 // If the argument type is an array type, move the qualifiers up to the
1123 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001124 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001125 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001126 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001127 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001128 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001129 RecanonicalizeArg = true;
1130 }
1131 }
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001133 // The argument type can not be less qualified than the parameter
1134 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001135 if (!(TDF & TDF_IgnoreQualifiers) &&
1136 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001137 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001138 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001139 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001140 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001141 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001142
Richard Smith87d263e2016-12-25 08:05:23 +00001143 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1144 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001145 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001146 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001147
Douglas Gregor1d684c22011-04-28 00:56:09 +00001148 // Remove any qualifiers on the parameter from the deduced type.
1149 // We checked the qualifiers for consistency above.
1150 Qualifiers DeducedQs = DeducedType.getQualifiers();
1151 Qualifiers ParamQs = Param.getQualifiers();
1152 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1153 if (ParamQs.hasObjCGCAttr())
1154 DeducedQs.removeObjCGCAttr();
1155 if (ParamQs.hasAddressSpace())
1156 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001157 if (ParamQs.hasObjCLifetime())
1158 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001159
Douglas Gregore46db902011-06-17 22:11:49 +00001160 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001161 // If template deduction would produce a lifetime qualifier on a type
1162 // that is not a lifetime type, template argument deduction fails.
1163 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1164 !DeducedType->isDependentType()) {
1165 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1166 Info.FirstArg = TemplateArgument(Param);
1167 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001168 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001169 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001170
Douglas Gregora4f2b432011-07-26 14:53:44 +00001171 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001172 // If template deduction would produce an argument type with lifetime type
1173 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001174 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001175 DeducedType->isObjCLifetimeType() &&
1176 !DeducedQs.hasObjCLifetime())
1177 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001178
Douglas Gregor1d684c22011-04-28 00:56:09 +00001179 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1180 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001181
Douglas Gregord6605db2009-07-22 21:30:48 +00001182 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001183 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Richard Smith5f274382016-09-28 23:55:27 +00001185 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001187 Deduced[Index],
1188 NewDeduced);
1189 if (Result.isNull()) {
1190 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1191 Info.FirstArg = Deduced[Index];
1192 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001196 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001198 }
1199
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001200 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001201 Info.FirstArg = TemplateArgument(ParamIn);
1202 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001203
Douglas Gregorfb322d82011-01-14 05:11:40 +00001204 // If the parameter is an already-substituted template parameter
1205 // pack, do nothing: we don't know which of its arguments to look
1206 // at, so we have to wait until all of the parameter packs in this
1207 // expansion have arguments.
1208 if (isa<SubstTemplateTypeParmPackType>(Param))
1209 return Sema::TDK_Success;
1210
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001211 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001212 CanQualType CanParam = S.Context.getCanonicalType(Param);
1213 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001214 if (!(TDF & TDF_IgnoreQualifiers)) {
1215 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001216 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001217 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001218 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001219 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001220 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001221 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001222
Douglas Gregor194ea692012-03-11 03:29:50 +00001223 // If the parameter type is not dependent, there is nothing to deduce.
1224 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001225 if (!(TDF & TDF_SkipNonDependent)) {
1226 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1227 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1228 Param != Arg;
1229 if (NonDeduced) {
1230 return Sema::TDK_NonDeducedMismatch;
1231 }
1232 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001233 return Sema::TDK_Success;
1234 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001235 } else if (!Param->isDependentType()) {
1236 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1237 ArgUnqualType = CanArg.getUnqualifiedType();
1238 bool Success = (TDF & TDF_InOverloadResolution)?
1239 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1240 ArgUnqualType) :
1241 ParamUnqualType == ArgUnqualType;
1242 if (Success)
1243 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001244 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001245
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001246 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001247 // Non-canonical types cannot appear here.
1248#define NON_CANONICAL_TYPE(Class, Base) \
1249 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1250#define TYPE(Class, Base)
1251#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001252
Douglas Gregor39c02722011-06-15 16:02:29 +00001253 case Type::TemplateTypeParm:
1254 case Type::SubstTemplateTypeParmPack:
1255 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001256
1257 // These types cannot be dependent, so simply check whether the types are
1258 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001259 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001260 case Type::VariableArray:
1261 case Type::Vector:
1262 case Type::FunctionNoProto:
1263 case Type::Record:
1264 case Type::Enum:
1265 case Type::ObjCObject:
1266 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001267 case Type::ObjCObjectPointer: {
1268 if (TDF & TDF_SkipNonDependent)
1269 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001270
Douglas Gregor194ea692012-03-11 03:29:50 +00001271 if (TDF & TDF_IgnoreQualifiers) {
1272 Param = Param.getUnqualifiedType();
1273 Arg = Arg.getUnqualifiedType();
1274 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001275
Douglas Gregor194ea692012-03-11 03:29:50 +00001276 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1277 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001278
1279 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001280 case Type::Complex:
1281 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001282 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1283 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001284 ComplexArg->getElementType(),
1285 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001286
1287 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001288
1289 // _Atomic T [extension]
1290 case Type::Atomic:
1291 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001292 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001293 cast<AtomicType>(Param)->getValueType(),
1294 AtomicArg->getValueType(),
1295 Info, Deduced, TDF);
1296
1297 return Sema::TDK_NonDeducedMismatch;
1298
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001299 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001300 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001301 QualType PointeeType;
1302 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1303 PointeeType = PointerArg->getPointeeType();
1304 } else if (const ObjCObjectPointerType *PointerArg
1305 = Arg->getAs<ObjCObjectPointerType>()) {
1306 PointeeType = PointerArg->getPointeeType();
1307 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001308 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Douglas Gregorfc516c92009-06-26 23:27:24 +00001311 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001312 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1313 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001314 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001315 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001318 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001319 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001320 const LValueReferenceType *ReferenceArg =
1321 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001322 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001323 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001324
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001325 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001326 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001327 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001328 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001329
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001330 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001331 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001332 const RValueReferenceType *ReferenceArg =
1333 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001334 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1338 cast<RValueReferenceType>(Param)->getPointeeType(),
1339 ReferenceArg->getPointeeType(),
1340 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001343 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001345 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001346 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001347 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001348 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001349
John McCallf7332682010-08-19 00:20:19 +00001350 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001351 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1352 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1353 IncompleteArrayArg->getElementType(),
1354 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001355 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001356
1357 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001359 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001360 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001361 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001362 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001363
1364 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001365 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001366 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
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;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001370 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1371 ConstantArrayParm->getElementType(),
1372 ConstantArrayArg->getElementType(),
1373 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001374 }
1375
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001376 // type [i]
1377 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001378 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001379 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001380 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001381
John McCallf7332682010-08-19 00:20:19 +00001382 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1383
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001384 // Check the element type of the arrays
1385 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001386 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001387 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001388 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1389 DependentArrayParm->getElementType(),
1390 ArrayArg->getElementType(),
1391 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001392 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001393
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001394 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001395 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001396 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001397 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001398 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001399
1400 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001402 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1403 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001404 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001405 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1406 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001407 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001408 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001409 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001410 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001411 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001412 if (const DependentSizedArrayType *DependentArrayArg
1413 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001414 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001415 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001416 DependentArrayArg->getSizeExpr(),
1417 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001419 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001420 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
1423 // type(*)(T)
1424 // T(*)()
1425 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001426 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001427 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001428 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001429 dyn_cast<FunctionProtoType>(Arg);
1430 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001434 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001437 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001439 != FunctionProtoArg->getRefQualifier() ||
1440 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001441 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001442
Anders Carlsson2128ec72009-06-08 15:19:08 +00001443 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001444 if (Sema::TemplateDeductionResult Result =
1445 DeduceTemplateArgumentsByTypeMatch(
1446 S, TemplateParams, FunctionProtoParam->getReturnType(),
1447 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001448 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001449
Alp Toker9cacbab2014-01-20 20:26:09 +00001450 return DeduceTemplateArguments(
1451 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1452 FunctionProtoParam->getNumParams(),
1453 FunctionProtoArg->param_type_begin(),
1454 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCalle78aac42010-03-10 03:28:59 +00001457 case Type::InjectedClassName: {
1458 // Treat a template's injected-class-name as if the template
1459 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001460 Param = cast<InjectedClassNameType>(Param)
1461 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001462 assert(isa<TemplateSpecializationType>(Param) &&
1463 "injected class name is not a template specialization type");
1464 // fall through
1465 }
1466
Douglas Gregor705c9002009-06-26 20:57:09 +00001467 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001468 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001469 // TT<T>
1470 // TT<i>
1471 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001472 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001473 const TemplateSpecializationType *SpecParam =
1474 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Richard Smith9b296e32016-04-25 19:09:05 +00001476 // When Arg cannot be a derived class, we can just try to deduce template
1477 // arguments from the template-id.
1478 const RecordType *RecordT = Arg->getAs<RecordType>();
1479 if (!(TDF & TDF_DerivedClass) || !RecordT)
1480 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1481 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Richard Smith9b296e32016-04-25 19:09:05 +00001483 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1484 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001485
Richard Smith9b296e32016-04-25 19:09:05 +00001486 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1487 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Richard Smith9b296e32016-04-25 19:09:05 +00001489 if (Result == Sema::TDK_Success)
1490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001491
Richard Smith9b296e32016-04-25 19:09:05 +00001492 // We cannot inspect base classes as part of deduction when the type
1493 // is incomplete, so either instantiate any templates necessary to
1494 // complete the type, or skip over it if it cannot be completed.
1495 if (!S.isCompleteType(Info.getLocation(), Arg))
1496 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Richard Smith9b296e32016-04-25 19:09:05 +00001498 // C++14 [temp.deduct.call] p4b3:
1499 // If P is a class and P has the form simple-template-id, then the
1500 // transformed A can be a derived class of the deduced A. Likewise if
1501 // P is a pointer to a class of the form simple-template-id, the
1502 // transformed A can be a pointer to a derived class pointed to by the
1503 // deduced A.
1504 //
1505 // These alternatives are considered only if type deduction would
1506 // otherwise fail. If they yield more than one possible deduced A, the
1507 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001508
Faisal Vali683b0742016-05-19 02:28:21 +00001509 // Reset the incorrectly deduced argument from above.
1510 Deduced = DeducedOrig;
1511
1512 // Use data recursion to crawl through the list of base classes.
1513 // Visited contains the set of nodes we have already visited, while
1514 // ToVisit is our stack of records that we still need to visit.
1515 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1516 SmallVector<const RecordType *, 8> ToVisit;
1517 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001518 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001519 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001520 while (!ToVisit.empty()) {
1521 // Retrieve the next class in the inheritance hierarchy.
1522 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001523
Faisal Vali683b0742016-05-19 02:28:21 +00001524 // If we have already seen this type, skip it.
1525 if (!Visited.insert(NextT).second)
1526 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001527
Faisal Vali683b0742016-05-19 02:28:21 +00001528 // If this is a base class, try to perform template argument
1529 // deduction from it.
1530 if (NextT != RecordT) {
1531 TemplateDeductionInfo BaseInfo(Info.getLocation());
1532 Sema::TemplateDeductionResult BaseResult =
1533 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1534 QualType(NextT, 0), BaseInfo, Deduced);
1535
1536 // If template argument deduction for this base was successful,
1537 // note that we had some success. Otherwise, ignore any deductions
1538 // from this base class.
1539 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001540 // If we've already seen some success, then deduction fails due to
1541 // an ambiguity (temp.deduct.call p5).
1542 if (Successful)
1543 return Sema::TDK_MiscellaneousDeductionFailure;
1544
Faisal Vali683b0742016-05-19 02:28:21 +00001545 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001546 std::swap(SuccessfulDeduced, Deduced);
1547
Faisal Vali683b0742016-05-19 02:28:21 +00001548 Info.Param = BaseInfo.Param;
1549 Info.FirstArg = BaseInfo.FirstArg;
1550 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 }
1552
1553 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Faisal Vali683b0742016-05-19 02:28:21 +00001556 // Visit base classes
1557 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1558 for (const auto &Base : Next->bases()) {
1559 assert(Base.getType()->isRecordType() &&
1560 "Base class that isn't a record?");
1561 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1562 }
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001565 if (Successful) {
1566 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001567 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001568 }
Richard Smith9b296e32016-04-25 19:09:05 +00001569
Douglas Gregore81f3e72009-07-07 23:09:34 +00001570 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001571 }
1572
Douglas Gregor637d9982009-06-10 23:47:09 +00001573 // T type::*
1574 // T T::*
1575 // T (type::*)()
1576 // type (T::*)()
1577 // type (type::*)(T)
1578 // type (T::*)(T)
1579 // T (type::*)(T)
1580 // T (T::*)()
1581 // T (T::*)(T)
1582 case Type::MemberPointer: {
1583 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1584 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1585 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001586 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001587
David Majnemera381cda2015-11-30 20:34:28 +00001588 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1589 if (ParamPointeeType->isFunctionType())
1590 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1591 /*IsCtorOrDtor=*/false, Info.getLocation());
1592 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1593 if (ArgPointeeType->isFunctionType())
1594 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1595 /*IsCtorOrDtor=*/false, Info.getLocation());
1596
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001597 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001598 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001599 ParamPointeeType,
1600 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001601 Info, Deduced,
1602 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001603 return Result;
1604
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001605 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606 QualType(MemPtrParam->getClass(), 0),
1607 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001608 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001609 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001610 }
1611
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001612 // (clang extension)
1613 //
Mike Stump11289f42009-09-09 15:08:12 +00001614 // type(^)(T)
1615 // T(^)()
1616 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001617 case Type::BlockPointer: {
1618 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1619 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlssona767eee2009-06-12 16:23:10 +00001621 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001622 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001624 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1625 BlockPtrParam->getPointeeType(),
1626 BlockPtrArg->getPointeeType(),
1627 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001628 }
1629
Douglas Gregor39c02722011-06-15 16:02:29 +00001630 // (clang extension)
1631 //
1632 // T __attribute__(((ext_vector_type(<integral constant>))))
1633 case Type::ExtVector: {
1634 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1635 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1636 // Make sure that the vectors have the same number of elements.
1637 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1638 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001639
Douglas Gregor39c02722011-06-15 16:02:29 +00001640 // 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
1647 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001648 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1649 // We can't check the number of elements, since the argument has a
1650 // dependent number of elements. This can only occur during partial
1651 // ordering.
1652
1653 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001654 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1655 VectorParam->getElementType(),
1656 VectorArg->getElementType(),
1657 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001658 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001659
Douglas Gregor39c02722011-06-15 16:02:29 +00001660 return Sema::TDK_NonDeducedMismatch;
1661 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001662
Douglas Gregor39c02722011-06-15 16:02:29 +00001663 // (clang extension)
1664 //
1665 // T __attribute__(((ext_vector_type(N))))
1666 case Type::DependentSizedExtVector: {
1667 const DependentSizedExtVectorType *VectorParam
1668 = cast<DependentSizedExtVectorType>(Param);
1669
1670 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1671 // Perform deduction on the element types.
1672 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001673 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1674 VectorParam->getElementType(),
1675 VectorArg->getElementType(),
1676 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001677 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001678
Douglas Gregor39c02722011-06-15 16:02:29 +00001679 // Perform deduction on the vector size, if we can.
1680 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001681 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001682 if (!NTTP)
1683 return Sema::TDK_Success;
1684
1685 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1686 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001687 // Note that we use the "array bound" rules here; just like in that
1688 // case, we don't have any particular type for the vector size, but
1689 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001690 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001691 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001692 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001693 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001694
1695 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001696 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1697 // Perform deduction on the element types.
1698 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001699 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1700 VectorParam->getElementType(),
1701 VectorArg->getElementType(),
1702 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001703 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001704
Douglas Gregor39c02722011-06-15 16:02:29 +00001705 // Perform deduction on the vector size, if we can.
1706 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001707 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001708 if (!NTTP)
1709 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001710
Richard Smith5f274382016-09-28 23:55:27 +00001711 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1712 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001713 Info, Deduced);
1714 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001715
Douglas Gregor39c02722011-06-15 16:02:29 +00001716 return Sema::TDK_NonDeducedMismatch;
1717 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001718
Douglas Gregor637d9982009-06-10 23:47:09 +00001719 case Type::TypeOfExpr:
1720 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001721 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001722 case Type::UnresolvedUsing:
1723 case Type::Decltype:
1724 case Type::UnaryTransform:
1725 case Type::Auto:
1726 case Type::DependentTemplateSpecialization:
1727 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001728 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001729 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001730 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001731 }
1732
David Blaikiee4d798f2012-01-20 21:50:17 +00001733 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001734}
1735
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001736static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001737DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001738 TemplateParameterList *TemplateParams,
1739 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001740 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001741 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001742 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001743 // If the template argument is a pack expansion, perform template argument
1744 // deduction against the pattern of that expansion. This only occurs during
1745 // partial ordering.
1746 if (Arg.isPackExpansion())
1747 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001749 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001750 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001751 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001752
1753 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001754 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001755 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1756 Param.getAsType(),
1757 Arg.getAsType(),
1758 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001759 Info.FirstArg = Param;
1760 Info.SecondArg = Arg;
1761 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001762
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001763 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001764 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001766 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001767 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001768 Info.FirstArg = Param;
1769 Info.SecondArg = Arg;
1770 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001771
1772 case TemplateArgument::TemplateExpansion:
1773 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001775 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001776 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001777 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001778 return Sema::TDK_Success;
1779
1780 Info.FirstArg = Param;
1781 Info.SecondArg = Arg;
1782 return Sema::TDK_NonDeducedMismatch;
1783
1784 case TemplateArgument::NullPtr:
1785 if (Arg.getKind() == TemplateArgument::NullPtr &&
1786 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001787 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001789 Info.FirstArg = Param;
1790 Info.SecondArg = Arg;
1791 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001792
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001793 case TemplateArgument::Integral:
1794 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001795 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001796 return Sema::TDK_Success;
1797
1798 Info.FirstArg = Param;
1799 Info.SecondArg = Arg;
1800 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001801 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001802
1803 if (Arg.getKind() == TemplateArgument::Expression) {
1804 Info.FirstArg = Param;
1805 Info.SecondArg = Arg;
1806 return Sema::TDK_NonDeducedMismatch;
1807 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001808
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001809 Info.FirstArg = Param;
1810 Info.SecondArg = Arg;
1811 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001813 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001814 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001815 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001816 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001817 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001818 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001819 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001820 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001821 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001822 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001823 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1824 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001825 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001826 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001827 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1828 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001829 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001830 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1831 Arg.getAsDecl(),
1832 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001833 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001834
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001835 Info.FirstArg = Param;
1836 Info.SecondArg = Arg;
1837 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001840 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001841 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001842 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001843 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001844 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
David Blaikiee4d798f2012-01-20 21:50:17 +00001847 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001848}
1849
Douglas Gregor7baabef2010-12-22 18:17:10 +00001850/// \brief Determine whether there is a template argument to be used for
1851/// deduction.
1852///
1853/// This routine "expands" argument packs in-place, overriding its input
1854/// parameters so that \c Args[ArgIdx] will be the available template argument.
1855///
1856/// \returns true if there is another template argument (which will be at
1857/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001858static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1859 unsigned &ArgIdx) {
1860 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001861 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor7baabef2010-12-22 18:17:10 +00001863 const TemplateArgument &Arg = Args[ArgIdx];
1864 if (Arg.getKind() != TemplateArgument::Pack)
1865 return true;
1866
Richard Smith0bda5b52016-12-23 23:46:56 +00001867 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1868 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001870 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871}
1872
Douglas Gregord0ad2942010-12-23 01:24:45 +00001873/// \brief Determine whether the given set of template arguments has a pack
1874/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001875static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1876 bool FoundPackExpansion = false;
1877 for (const auto &A : Args) {
1878 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001879 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001880
1881 if (A.getKind() == TemplateArgument::Pack)
1882 return hasPackExpansionBeforeEnd(A.pack_elements());
1883
1884 if (A.isPackExpansion())
1885 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Douglas Gregord0ad2942010-12-23 01:24:45 +00001888 return false;
1889}
1890
Douglas Gregor7baabef2010-12-22 18:17:10 +00001891static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001892DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001893 ArrayRef<TemplateArgument> Params,
1894 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001896 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1897 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001898 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899 // If the template argument list of P contains a pack expansion that is not
1900 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001901 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001902 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001903 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001905 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906 // If P has a form that contains <T> or <i>, then each argument Pi of the
1907 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001908 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001909 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001910 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001911 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001912 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913
Douglas Gregor7baabef2010-12-22 18:17:10 +00001914 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001915 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001916 return NumberOfArgumentsMustMatch
1917 ? Sema::TDK_MiscellaneousDeductionFailure
1918 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
Richard Smith26b86ea2016-12-31 21:41:23 +00001920 // C++1z [temp.deduct.type]p9:
1921 // During partial ordering, if Ai was originally a pack expansion [and]
1922 // Pi is not a pack expansion, template argument deduction fails.
1923 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001924 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001926 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001927 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001928 = DeduceTemplateArguments(S, TemplateParams,
1929 Params[ParamIdx], Args[ArgIdx],
1930 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931 return Result;
1932
Douglas Gregor7baabef2010-12-22 18:17:10 +00001933 // Move to the next argument.
1934 ++ArgIdx;
1935 continue;
1936 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001938 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001940 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941 // If Pi is a pack expansion, then the pattern of Pi is compared with
1942 // each remaining argument in the template argument list of A. Each
1943 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001944 // template parameter packs expanded by Pi.
1945 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 // FIXME: If there are no remaining arguments, we can bail out early
1948 // and set any deduced parameter packs to an empty argument pack.
1949 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Richard Smith0a80d572014-05-29 01:12:14 +00001951 // Prepare to deduce the packs within the pattern.
1952 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001953
1954 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001956 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001957 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001958 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001960 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1961 Info, Deduced))
1962 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Richard Smith0a80d572014-05-29 01:12:14 +00001964 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001967 // Build argument packs for each of the parameter packs expanded by this
1968 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001969 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Douglas Gregor7baabef2010-12-22 18:17:10 +00001973 return Sema::TDK_Success;
1974}
1975
Mike Stump11289f42009-09-09 15:08:12 +00001976static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001977DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001978 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001979 const TemplateArgumentList &ParamList,
1980 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001981 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001982 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001983 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00001984 ArgList.asArray(), Info, Deduced,
1985 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001986}
1987
Douglas Gregor705c9002009-06-26 20:57:09 +00001988/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001989static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00001990 TemplateArgument X,
1991 const TemplateArgument &Y,
1992 bool PackExpansionMatchesPack = false) {
1993 // If we're checking deduced arguments (X) against original arguments (Y),
1994 // we will have flattened packs to non-expansions in X.
1995 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1996 X = X.getPackExpansionPattern();
1997
Douglas Gregor705c9002009-06-26 20:57:09 +00001998 if (X.getKind() != Y.getKind())
1999 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor705c9002009-06-26 20:57:09 +00002001 switch (X.getKind()) {
2002 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002003 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002004
Douglas Gregor705c9002009-06-26 20:57:09 +00002005 case TemplateArgument::Type:
2006 return Context.getCanonicalType(X.getAsType()) ==
2007 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor705c9002009-06-26 20:57:09 +00002009 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002010 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002011
2012 case TemplateArgument::NullPtr:
2013 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002014
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002015 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002016 case TemplateArgument::TemplateExpansion:
2017 return Context.getCanonicalTemplateName(
2018 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2019 Context.getCanonicalTemplateName(
2020 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
Douglas Gregor705c9002009-06-26 20:57:09 +00002022 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002023 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002024
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002025 case TemplateArgument::Expression: {
2026 llvm::FoldingSetNodeID XID, YID;
2027 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002029 return XID == YID;
2030 }
Mike Stump11289f42009-09-09 15:08:12 +00002031
Douglas Gregor705c9002009-06-26 20:57:09 +00002032 case TemplateArgument::Pack:
2033 if (X.pack_size() != Y.pack_size())
2034 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002035
2036 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2037 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002038 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002039 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002040 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002041 return false;
2042
2043 return true;
2044 }
2045
David Blaikiee4d798f2012-01-20 21:50:17 +00002046 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002047}
2048
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049/// \brief Allocate a TemplateArgumentLoc where all locations have
2050/// been initialized to the given location.
2051///
James Dennett634962f2012-06-14 21:40:34 +00002052/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002053/// location information for.
2054///
2055/// \param NTTPType For a declaration template argument, the type of
2056/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002057/// argument. Can be null if no type sugar is available to add to the
2058/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002059///
2060/// \param Loc The source location to use for the resulting template
2061/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002062TemplateArgumentLoc
2063Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2064 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002065 switch (Arg.getKind()) {
2066 case TemplateArgument::Null:
2067 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068
Douglas Gregorca4686d2011-01-04 23:35:54 +00002069 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002070 return TemplateArgumentLoc(
2071 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Douglas Gregorca4686d2011-01-04 23:35:54 +00002073 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002074 if (NTTPType.isNull())
2075 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002076 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2077 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002078 return TemplateArgumentLoc(TemplateArgument(E), E);
2079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080
Eli Friedmanb826a002012-09-26 02:36:12 +00002081 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002082 if (NTTPType.isNull())
2083 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002084 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2085 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002086 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2087 E);
2088 }
2089
Douglas Gregorca4686d2011-01-04 23:35:54 +00002090 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002091 Expr *E =
2092 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002093 return TemplateArgumentLoc(TemplateArgument(E), E);
2094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Douglas Gregor9d802122011-03-02 17:09:35 +00002096 case TemplateArgument::Template:
2097 case TemplateArgument::TemplateExpansion: {
2098 NestedNameSpecifierLocBuilder Builder;
2099 TemplateName Template = Arg.getAsTemplate();
2100 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002101 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002102 else if (QualifiedTemplateName *QTN =
2103 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002104 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002105
Douglas Gregor9d802122011-03-02 17:09:35 +00002106 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002107 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002108 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002109
2110 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002111 Loc, Loc);
2112 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002113
Douglas Gregorca4686d2011-01-04 23:35:54 +00002114 case TemplateArgument::Expression:
2115 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 case TemplateArgument::Pack:
2118 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002120
David Blaikiee4d798f2012-01-20 21:50:17 +00002121 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002122}
2123
2124
2125/// \brief Convert the given deduced template argument and add it to the set of
2126/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002127static bool
2128ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2129 DeducedTemplateArgument Arg,
2130 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002131 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002132 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002133 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002134 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2135 unsigned ArgumentPackIndex) {
2136 // Convert the deduced template argument into a template
2137 // argument that we can check, almost as if the user had written
2138 // the template argument explicitly.
2139 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002140 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002141
2142 // Check the template argument, converting it as necessary.
2143 return S.CheckTemplateArgument(
2144 Param, ArgLoc, Template, Template->getLocation(),
2145 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002146 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002147 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2148 : Sema::CTAK_Deduced)
2149 : Sema::CTAK_Specified);
2150 };
2151
Douglas Gregorca4686d2011-01-04 23:35:54 +00002152 if (Arg.getKind() == TemplateArgument::Pack) {
2153 // This is a template argument pack, so check each of its arguments against
2154 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002155 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002156 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002157 // When converting the deduced template argument, append it to the
2158 // general output list. We need to do this so that the template argument
2159 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002160 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002161 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002162 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2163 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002164 if (P.isNull()) {
2165 // We deduced arguments for some elements of this pack, but not for
2166 // all of them. This happens if we get a conditionally-non-deduced
2167 // context in a pack expansion (such as an overload set in one of the
2168 // arguments).
2169 S.Diag(Param->getLocation(),
2170 diag::err_template_arg_deduced_incomplete_pack)
2171 << Arg << Param;
2172 return true;
2173 }
Richard Smith37acb792016-02-03 20:15:01 +00002174 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002175 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregor51bc5712011-01-05 20:52:18 +00002177 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002178 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
Richard Smithdf18ee92016-02-03 20:40:30 +00002181 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002182 // itself, in case that substitution fails.
2183 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002184 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002185 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002186 MultiLevelTemplateArgumentList Args(TemplateArgs);
2187
2188 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2189 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2190 NTTP, Output,
2191 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002192 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002193 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2194 NTTP->getDeclName()).isNull())
2195 return true;
2196 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2197 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2198 TTP, Output,
2199 Template->getSourceRange());
2200 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2201 return true;
2202 }
2203 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002204 }
Richard Smith37acb792016-02-03 20:15:01 +00002205
Douglas Gregorca4686d2011-01-04 23:35:54 +00002206 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002207 Output.push_back(
2208 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002209 return false;
2210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002211
Richard Smith37acb792016-02-03 20:15:01 +00002212 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002213}
2214
Richard Smith1f5be4d2016-12-21 01:10:31 +00002215// FIXME: This should not be a template, but
2216// ClassTemplatePartialSpecializationDecl sadly does not derive from
2217// TemplateDecl.
2218template<typename TemplateDeclT>
2219static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002220 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002221 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2222 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2223 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2224 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2225 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2226
2227 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2228 NamedDecl *Param = TemplateParams->getParam(I);
2229
2230 if (!Deduced[I].isNull()) {
2231 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002232 // We may have had explicitly-specified template arguments for a
2233 // template parameter pack (that may or may not have been extended
2234 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002235 if (Param->isParameterPack() && CurrentInstantiationScope &&
2236 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2237 // Forget the partially-substituted pack; its substitution is now
2238 // complete.
2239 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2240 // We still need to check the argument in case it was extended by
2241 // deduction.
2242 } else {
2243 // We have already fully type-checked and converted this
2244 // argument, because it was explicitly-specified. Just record the
2245 // presence of this argument.
2246 Builder.push_back(Deduced[I]);
2247 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002248 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002249 }
2250
Richard Smith9c0c9862017-01-05 20:27:28 +00002251 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002252 // checked and converted.
2253 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002254 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002255 Info.Param = makeTemplateParameter(Param);
2256 // FIXME: These template arguments are temporary. Free them!
2257 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2258 return Sema::TDK_SubstitutionFailure;
2259 }
2260
2261 continue;
2262 }
2263
2264 // C++0x [temp.arg.explicit]p3:
2265 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2266 // be deduced to an empty sequence of template arguments.
2267 // FIXME: Where did the word "trailing" come from?
2268 if (Param->isTemplateParameterPack()) {
2269 // We may have had explicitly-specified template arguments for this
2270 // template parameter pack. If so, our empty deduction extends the
2271 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2272 const TemplateArgument *ExplicitArgs;
2273 unsigned NumExplicitArgs;
2274 if (CurrentInstantiationScope &&
2275 CurrentInstantiationScope->getPartiallySubstitutedPack(
2276 &ExplicitArgs, &NumExplicitArgs) == Param) {
2277 Builder.push_back(TemplateArgument(
2278 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2279
2280 // Forget the partially-substituted pack; its substitution is now
2281 // complete.
2282 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2283 } else {
2284 // Go through the motions of checking the empty argument pack against
2285 // the parameter pack.
2286 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002287 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2288 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002289 Info.Param = makeTemplateParameter(Param);
2290 // FIXME: These template arguments are temporary. Free them!
2291 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2292 return Sema::TDK_SubstitutionFailure;
2293 }
2294 }
2295 continue;
2296 }
2297
2298 // Substitute into the default template argument, if available.
2299 bool HasDefaultArg = false;
2300 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2301 if (!TD) {
2302 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2303 return Sema::TDK_Incomplete;
2304 }
2305
2306 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2307 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2308 HasDefaultArg);
2309
2310 // If there was no default argument, deduction is incomplete.
2311 if (DefArg.getArgument().isNull()) {
2312 Info.Param = makeTemplateParameter(
2313 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2314 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2315 if (PartialOverloading) break;
2316
2317 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2318 : Sema::TDK_Incomplete;
2319 }
2320
2321 // Check whether we can actually use the default argument.
2322 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2323 TD->getSourceRange().getEnd(), 0, Builder,
2324 Sema::CTAK_Specified)) {
2325 Info.Param = makeTemplateParameter(
2326 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2327 // FIXME: These template arguments are temporary. Free them!
2328 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2329 return Sema::TDK_SubstitutionFailure;
2330 }
2331
2332 // If we get here, we successfully used the default template argument.
2333 }
2334
2335 return Sema::TDK_Success;
2336}
2337
Richard Smith0da6dc42016-12-24 16:40:51 +00002338DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2339 if (auto *DC = dyn_cast<DeclContext>(D))
2340 return DC;
2341 return D->getDeclContext();
2342}
2343
2344template<typename T> struct IsPartialSpecialization {
2345 static constexpr bool value = false;
2346};
2347template<>
2348struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2349 static constexpr bool value = true;
2350};
2351template<>
2352struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2353 static constexpr bool value = true;
2354};
2355
2356/// Complete template argument deduction for a partial specialization.
2357template <typename T>
2358static typename std::enable_if<IsPartialSpecialization<T>::value,
2359 Sema::TemplateDeductionResult>::type
2360FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002361 Sema &S, T *Partial, bool IsPartialOrdering,
2362 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002363 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2364 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002365 // Unevaluated SFINAE context.
2366 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002367 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368
Richard Smith0da6dc42016-12-24 16:40:51 +00002369 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002370
2371 // C++ [temp.deduct.type]p2:
2372 // [...] or if any template argument remains neither deduced nor
2373 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002374 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002375 if (auto Result = ConvertDeducedTemplateArguments(
2376 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002377 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378
Douglas Gregor684268d2010-04-29 06:21:43 +00002379 // Form the template argument list from the deduced template arguments.
2380 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002381 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002382
Douglas Gregor684268d2010-04-29 06:21:43 +00002383 Info.reset(DeducedArgumentList);
2384
2385 // Substitute the deduced template arguments into the template
2386 // arguments of the class template partial specialization, and
2387 // verify that the instantiated template arguments are both valid
2388 // and are equivalent to the template arguments originally provided
2389 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002390 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002391 auto *Template = Partial->getSpecializedTemplate();
2392 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2393 Partial->getTemplateArgsAsWritten();
2394 const TemplateArgumentLoc *PartialTemplateArgs =
2395 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002396
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002397 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2398 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002399
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002400 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002401 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2402 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2403 if (ParamIdx >= Partial->getTemplateParameters()->size())
2404 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2405
Richard Smith0da6dc42016-12-24 16:40:51 +00002406 Decl *Param = const_cast<NamedDecl *>(
2407 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002408 Info.Param = makeTemplateParameter(Param);
2409 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2410 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002411 }
2412
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002413 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002414 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2415 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002416 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417
Richard Smith0da6dc42016-12-24 16:40:51 +00002418 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002419 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002420 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002421 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002422 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002423 Info.FirstArg = TemplateArgs[I];
2424 Info.SecondArg = InstArg;
2425 return Sema::TDK_NonDeducedMismatch;
2426 }
2427 }
2428
2429 if (Trap.hasErrorOccurred())
2430 return Sema::TDK_SubstitutionFailure;
2431
2432 return Sema::TDK_Success;
2433}
2434
Richard Smith0e617ec2016-12-27 07:56:27 +00002435/// Complete template argument deduction for a class or variable template,
2436/// when partial ordering against a partial specialization.
2437// FIXME: Factor out duplication with partial specialization version above.
2438Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2439 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2440 const TemplateArgumentList &TemplateArgs,
2441 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2442 TemplateDeductionInfo &Info) {
2443 // Unevaluated SFINAE context.
2444 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2445 Sema::SFINAETrap Trap(S);
2446
2447 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2448
2449 // C++ [temp.deduct.type]p2:
2450 // [...] or if any template argument remains neither deduced nor
2451 // explicitly specified, template argument deduction fails.
2452 SmallVector<TemplateArgument, 4> Builder;
2453 if (auto Result = ConvertDeducedTemplateArguments(
2454 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2455 return Result;
2456
2457 // Check that we produced the correct argument list.
2458 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2459 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2460 TemplateArgument InstArg = Builder[I];
2461 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2462 /*PackExpansionMatchesPack*/true)) {
2463 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2464 Info.FirstArg = TemplateArgs[I];
2465 Info.SecondArg = InstArg;
2466 return Sema::TDK_NonDeducedMismatch;
2467 }
2468 }
2469
2470 if (Trap.hasErrorOccurred())
2471 return Sema::TDK_SubstitutionFailure;
2472
2473 return Sema::TDK_Success;
2474}
2475
2476
Douglas Gregor170bc422009-06-12 22:31:52 +00002477/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002478/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002479/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002480Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002481Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002482 const TemplateArgumentList &TemplateArgs,
2483 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002484 if (Partial->isInvalidDecl())
2485 return TDK_Invalid;
2486
Douglas Gregor170bc422009-06-12 22:31:52 +00002487 // C++ [temp.class.spec.match]p2:
2488 // A partial specialization matches a given actual template
2489 // argument list if the template arguments of the partial
2490 // specialization can be deduced from the actual template argument
2491 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002492
2493 // Unevaluated SFINAE context.
2494 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002495 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002496
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002497 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002498 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002499 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002500 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002501 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002502 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002503 TemplateArgs, Info, Deduced))
2504 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002505
Richard Smith80934652012-07-16 01:09:10 +00002506 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002507 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2508 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002509 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002510 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002511
Douglas Gregore1416332009-06-14 08:02:22 +00002512 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002513 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514
Richard Smith87d263e2016-12-25 08:05:23 +00002515 return ::FinishTemplateArgumentDeduction(
2516 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002517}
Douglas Gregor91772d12009-06-13 00:26:55 +00002518
Larisse Voufo39a1e502013-08-06 01:03:05 +00002519/// \brief Perform template argument deduction to determine whether
2520/// the given template arguments match the given variable template
2521/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002522Sema::TemplateDeductionResult
2523Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2524 const TemplateArgumentList &TemplateArgs,
2525 TemplateDeductionInfo &Info) {
2526 if (Partial->isInvalidDecl())
2527 return TDK_Invalid;
2528
2529 // C++ [temp.class.spec.match]p2:
2530 // A partial specialization matches a given actual template
2531 // argument list if the template arguments of the partial
2532 // specialization can be deduced from the actual template argument
2533 // list (14.8.2).
2534
2535 // Unevaluated SFINAE context.
2536 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2537 SFINAETrap Trap(*this);
2538
2539 SmallVector<DeducedTemplateArgument, 4> Deduced;
2540 Deduced.resize(Partial->getTemplateParameters()->size());
2541 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2542 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2543 TemplateArgs, Info, Deduced))
2544 return Result;
2545
2546 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002547 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2548 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002549 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002550 return TDK_InstantiationDepth;
2551
2552 if (Trap.hasErrorOccurred())
2553 return Sema::TDK_SubstitutionFailure;
2554
Richard Smith87d263e2016-12-25 08:05:23 +00002555 return ::FinishTemplateArgumentDeduction(
2556 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002557}
2558
Douglas Gregorfc516c92009-06-26 23:27:24 +00002559/// \brief Determine whether the given type T is a simple-template-id type.
2560static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002561 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002562 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002563 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002564
Douglas Gregorfc516c92009-06-26 23:27:24 +00002565 return false;
2566}
Douglas Gregor9b146582009-07-08 20:55:45 +00002567
Richard Smithde0d34a2017-01-09 07:14:40 +00002568static void
2569MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
2570 bool OnlyDeduced,
2571 unsigned Level,
2572 llvm::SmallBitVector &Deduced);
2573
Douglas Gregor9b146582009-07-08 20:55:45 +00002574/// \brief Substitute the explicitly-provided template arguments into the
2575/// given function template according to C++ [temp.arg.explicit].
2576///
2577/// \param FunctionTemplate the function template into which the explicit
2578/// template arguments will be substituted.
2579///
James Dennett634962f2012-06-14 21:40:34 +00002580/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002581/// arguments.
2582///
Mike Stump11289f42009-09-09 15:08:12 +00002583/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002584/// with the converted and checked explicit template arguments.
2585///
Mike Stump11289f42009-09-09 15:08:12 +00002586/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002587/// parameters.
2588///
2589/// \param FunctionType if non-NULL, the result type of the function template
2590/// will also be instantiated and the pointed-to value will be updated with
2591/// the instantiated function type.
2592///
2593/// \param Info if substitution fails for any reason, this object will be
2594/// populated with more information about the failure.
2595///
2596/// \returns TDK_Success if substitution was successful, or some failure
2597/// condition.
2598Sema::TemplateDeductionResult
2599Sema::SubstituteExplicitTemplateArguments(
2600 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002601 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002602 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2603 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002604 QualType *FunctionType,
2605 TemplateDeductionInfo &Info) {
2606 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2607 TemplateParameterList *TemplateParams
2608 = FunctionTemplate->getTemplateParameters();
2609
John McCall6b51f282009-11-23 01:53:49 +00002610 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002611 // No arguments to substitute; just copy over the parameter types and
2612 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002613 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002614 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregor9b146582009-07-08 20:55:45 +00002616 if (FunctionType)
2617 *FunctionType = Function->getType();
2618 return TDK_Success;
2619 }
Mike Stump11289f42009-09-09 15:08:12 +00002620
Eli Friedman77dcc722012-02-08 03:07:05 +00002621 // Unevaluated SFINAE context.
2622 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002623 SFINAETrap Trap(*this);
2624
Douglas Gregor9b146582009-07-08 20:55:45 +00002625 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002626 // Template arguments that are present shall be specified in the
2627 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002628 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002629 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002630 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002631
2632 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002633 // explicitly-specified template arguments against this function template,
2634 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002635 SmallVector<TemplateArgument, 4> DeducedArgs;
Nick Lewycky56412332014-01-11 02:37:12 +00002636 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2637 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002638 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2639 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002640 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002641 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002642
Richard Smith11255ec2017-01-18 19:19:22 +00002643 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2644 ExplicitTemplateArgs, true, Builder, false) ||
2645 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002646 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002647 if (Index >= TemplateParams->size())
2648 Index = TemplateParams->size() - 1;
2649 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002650 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002651 }
Mike Stump11289f42009-09-09 15:08:12 +00002652
Douglas Gregor9b146582009-07-08 20:55:45 +00002653 // Form the template argument list from the explicitly-specified
2654 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002655 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002656 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002657 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
John McCall036855a2010-10-12 19:40:14 +00002659 // Template argument deduction and the final substitution should be
2660 // done in the context of the templated declaration. Explicit
2661 // argument substitution, on the other hand, needs to happen in the
2662 // calling context.
2663 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2664
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002666 // note that the template argument pack is partially substituted and record
2667 // the explicit template arguments. They'll be used as part of deduction
2668 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002669 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2670 const TemplateArgument &Arg = Builder[I];
2671 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002672 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002674 Arg.pack_begin(),
2675 Arg.pack_size());
2676 break;
2677 }
2678 }
2679
Richard Smith5e580292012-02-10 09:58:53 +00002680 const FunctionProtoType *Proto
2681 = Function->getType()->getAs<FunctionProtoType>();
2682 assert(Proto && "Function template does not have a prototype?");
2683
Richard Smith70b13042015-01-09 01:19:56 +00002684 // Isolate our substituted parameters from our caller.
2685 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2686
John McCallc8e321d2016-03-01 02:09:25 +00002687 ExtParameterInfoBuilder ExtParamInfos;
2688
Douglas Gregor9b146582009-07-08 20:55:45 +00002689 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002690 // explicitly-specified template arguments. If the function has a trailing
2691 // return type, substitute it after the arguments to ensure we substitute
2692 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002693 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002694 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002695 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002696 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002697 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002698 return TDK_SubstitutionFailure;
2699 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002700
Richard Smith5e580292012-02-10 09:58:53 +00002701 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002702 QualType ResultType;
2703 {
2704 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002705 // If a declaration declares a member function or member function
2706 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002707 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002708 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002709 // declarator.
2710 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002711 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002712 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2713 ThisContext = Method->getParent();
2714 ThisTypeQuals = Method->getTypeQualifiers();
2715 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002716
Douglas Gregor3024f072012-04-16 07:05:22 +00002717 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002718 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002719
2720 ResultType =
2721 SubstType(Proto->getReturnType(),
2722 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2723 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002724 if (ResultType.isNull() || Trap.hasErrorOccurred())
2725 return TDK_SubstitutionFailure;
2726 }
John McCallc8e321d2016-03-01 02:09:25 +00002727
Richard Smith5e580292012-02-10 09:58:53 +00002728 // Instantiate the types of each of the function parameters given the
2729 // explicitly-specified template arguments if we didn't do so earlier.
2730 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002731 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002732 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002733 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002734 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002735 return TDK_SubstitutionFailure;
2736
Douglas Gregor9b146582009-07-08 20:55:45 +00002737 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002738 auto EPI = Proto->getExtProtoInfo();
2739 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002740 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002741 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002742 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002743 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002744 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2745 return TDK_SubstitutionFailure;
2746 }
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregor9b146582009-07-08 20:55:45 +00002748 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002749 // Trailing template arguments that can be deduced (14.8.2) may be
2750 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002751 // template arguments can be deduced, they may all be omitted; in this
2752 // case, the empty template argument list <> itself may also be omitted.
2753 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002754 // Take all of the explicitly-specified arguments and put them into
2755 // the set of deduced template arguments. Explicitly-specified
2756 // parameter packs, however, will be set to NULL since the deduction
2757 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002758 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002759 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2760 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2761 if (Arg.getKind() == TemplateArgument::Pack)
2762 Deduced.push_back(DeducedTemplateArgument());
2763 else
2764 Deduced.push_back(Arg);
2765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Douglas Gregor9b146582009-07-08 20:55:45 +00002767 return TDK_Success;
2768}
2769
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002770/// \brief Check whether the deduced argument type for a call to a function
2771/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002772static bool
2773CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002774 QualType DeducedA) {
2775 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002776
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002777 QualType A = OriginalArg.OriginalArgType;
2778 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002779
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002780 // Check for type equality (top-level cv-qualifiers are ignored).
2781 if (Context.hasSameUnqualifiedType(A, DeducedA))
2782 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002783
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002784 // Strip off references on the argument types; they aren't needed for
2785 // the following checks.
2786 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2787 DeducedA = DeducedARef->getPointeeType();
2788 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2789 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002790
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002791 // C++ [temp.deduct.call]p4:
2792 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002793 // - If the original P is a reference type, the deduced A (i.e., the
2794 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002795 // the transformed A.
2796 if (const ReferenceType *OriginalParamRef
2797 = OriginalParamType->getAs<ReferenceType>()) {
2798 // We don't want to keep the reference around any more.
2799 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002800
Richard Smith1be59c52016-10-22 01:32:19 +00002801 // FIXME: Resolve core issue (no number yet): if the original P is a
2802 // reference type and the transformed A is function type "noexcept F",
2803 // the deduced A can be F.
2804 QualType Tmp;
2805 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2806 return false;
2807
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002808 Qualifiers AQuals = A.getQualifiers();
2809 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002810
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002811 // Under Objective-C++ ARC, the deduced type may have implicitly
2812 // been given strong or (when dealing with a const reference)
2813 // unsafe_unretained lifetime. If so, update the original
2814 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002815 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002816 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2817 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2818 (DeducedAQuals.hasConst() &&
2819 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2820 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002821 }
2822
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002823 if (AQuals == DeducedAQuals) {
2824 // Qualifiers match; there's nothing to do.
2825 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002826 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002827 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002828 // Qualifiers are compatible, so have the argument type adopt the
2829 // deduced argument type's qualifiers as if we had performed the
2830 // qualification conversion.
2831 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2832 }
2833 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002834
2835 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002836 // type that can be converted to the deduced A via a function pointer
2837 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002838 //
Richard Smith1be59c52016-10-22 01:32:19 +00002839 // Also allow conversions which merely strip __attribute__((noreturn)) from
2840 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002841 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002842 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002843 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002844 (S.IsQualificationConversion(A, DeducedA, false,
2845 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002846 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002847 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002848
Simon Pilgrim728134c2016-08-12 11:43:57 +00002849 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002850 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002851 // [...] Likewise, if P is a pointer to a class of the form
2852 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002853 // derived class pointed to by the deduced A.
2854 if (const PointerType *OriginalParamPtr
2855 = OriginalParamType->getAs<PointerType>()) {
2856 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2857 if (const PointerType *APtr = A->getAs<PointerType>()) {
2858 if (A->getPointeeType()->isRecordType()) {
2859 OriginalParamType = OriginalParamPtr->getPointeeType();
2860 DeducedA = DeducedAPtr->getPointeeType();
2861 A = APtr->getPointeeType();
2862 }
2863 }
2864 }
2865 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002866
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002867 if (Context.hasSameUnqualifiedType(A, DeducedA))
2868 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002869
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002870 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002871 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002872 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002873
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002874 return true;
2875}
2876
Richard Smithc92d2062017-01-05 23:02:44 +00002877/// Find the pack index for a particular parameter index in an instantiation of
2878/// a function template with specific arguments.
2879///
2880/// \return The pack index for whichever pack produced this parameter, or -1
2881/// if this was not produced by a parameter. Intended to be used as the
2882/// ArgumentPackSubstitutionIndex for further substitutions.
2883// FIXME: We should track this in OriginalCallArgs so we don't need to
2884// reconstruct it here.
2885static unsigned getPackIndexForParam(Sema &S,
2886 FunctionTemplateDecl *FunctionTemplate,
2887 const MultiLevelTemplateArgumentList &Args,
2888 unsigned ParamIdx) {
2889 unsigned Idx = 0;
2890 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2891 if (PD->isParameterPack()) {
2892 unsigned NumExpansions =
2893 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2894 if (Idx + NumExpansions > ParamIdx)
2895 return ParamIdx - Idx;
2896 Idx += NumExpansions;
2897 } else {
2898 if (Idx == ParamIdx)
2899 return -1; // Not a pack expansion
2900 ++Idx;
2901 }
2902 }
2903
2904 llvm_unreachable("parameter index would not be produced from template");
2905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002908/// checking the deduced template arguments for completeness and forming
2909/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002910///
2911/// \param OriginalCallArgs If non-NULL, the original call arguments against
2912/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00002913Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2914 FunctionTemplateDecl *FunctionTemplate,
2915 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2916 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
2917 TemplateDeductionInfo &Info,
2918 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2919 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002920 // Unevaluated SFINAE context.
2921 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002922 SFINAETrap Trap(*this);
2923
Douglas Gregor9b146582009-07-08 20:55:45 +00002924 // Enter a new template instantiation context while we instantiate the
2925 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002926 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002927 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2928 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002929 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2930 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002931 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002932 return TDK_InstantiationDepth;
2933
John McCalle23b8712010-04-29 01:18:58 +00002934 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002935
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002936 // C++ [temp.deduct.type]p2:
2937 // [...] or if any template argument remains neither deduced nor
2938 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002939 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002940 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002941 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002942 CurrentInstantiationScope, NumExplicitlySpecified,
2943 PartialOverloading))
2944 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002945
Richard Smith6eedfe72017-01-09 08:01:21 +00002946 // C++ [temp.deduct.call]p10: [DR1391]
2947 // If deduction succeeds for all parameters that contain
2948 // template-parameters that participate in template argument deduction,
2949 // and all template arguments are explicitly specified, deduced, or
2950 // obtained from default template arguments, remaining parameters are then
2951 // compared with the corresponding arguments. For each remaining parameter
2952 // P with a type that was non-dependent before substitution of any
2953 // explicitly-specified template arguments, if the corresponding argument
2954 // A cannot be implicitly converted to P, deduction fails.
2955 if (CheckNonDependent())
2956 return TDK_NonDependentConversionFailure;
2957
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002958 // Form the template argument list from the deduced template arguments.
2959 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002960 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002961 Info.reset(DeducedArgumentList);
2962
Mike Stump11289f42009-09-09 15:08:12 +00002963 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002964 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002965 DeclContext *Owner = FunctionTemplate->getDeclContext();
2966 if (FunctionTemplate->getFriendObjectKind())
2967 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00002968 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00002969 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00002970 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002971 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002972 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002973
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002975 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976
Mike Stump11289f42009-09-09 15:08:12 +00002977 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002978 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002979 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2980 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002981 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002982
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002983 // There may have been an error that did not prevent us from constructing a
2984 // declaration. Mark the declaration invalid and return with a substitution
2985 // failure.
2986 if (Trap.hasErrorOccurred()) {
2987 Specialization->setInvalidDecl(true);
2988 return TDK_SubstitutionFailure;
2989 }
2990
Douglas Gregore65aacb2011-06-16 16:50:48 +00002991 if (OriginalCallArgs) {
2992 // C++ [temp.deduct.call]p4:
2993 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002994 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002995 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00002996 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002997 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2998 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00002999
Richard Smithc92d2062017-01-05 23:02:44 +00003000 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003001 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003002 // FIXME: This presumably means a pack ended up smaller than we
3003 // expected while deducing. Should this not result in deduction
3004 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003005 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003006
Richard Smithc92d2062017-01-05 23:02:44 +00003007 QualType DeducedA;
3008 if (!OriginalArg.DecomposedParam) {
3009 // P is one of the function parameters, just look up its substituted
3010 // type.
3011 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3012 } else {
3013 // P is a decomposed element of a parameter corresponding to a
3014 // braced-init-list argument. Substitute back into P to find the
3015 // deduced A.
3016 QualType &CacheEntry =
3017 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3018 if (CacheEntry.isNull()) {
3019 ArgumentPackSubstitutionIndexRAII PackIndex(
3020 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3021 ParamIdx));
3022 CacheEntry =
3023 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3024 Specialization->getTypeSpecStartLoc(),
3025 Specialization->getDeclName());
3026 }
3027 DeducedA = CacheEntry;
3028 }
3029
Richard Smith9b534542015-12-31 02:02:54 +00003030 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3031 Info.FirstArg = TemplateArgument(DeducedA);
3032 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3033 Info.CallArgIndex = OriginalArg.ArgIdx;
Richard Smithc92d2062017-01-05 23:02:44 +00003034 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3035 : TDK_DeducedMismatch;
Richard Smith9b534542015-12-31 02:02:54 +00003036 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003037 }
3038 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003039
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003040 // If we suppressed any diagnostics while performing template argument
3041 // deduction, and if we haven't already instantiated this declaration,
3042 // keep track of these diagnostics. They'll be emitted if this specialization
3043 // is actually used.
3044 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003045 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003046 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3047 if (Pos == SuppressedDiagnostics.end())
3048 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3049 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003051
Mike Stump11289f42009-09-09 15:08:12 +00003052 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003053}
3054
John McCall8d08b9b2010-08-27 09:08:28 +00003055/// Gets the type of a function for template-argument-deducton
3056/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003057static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003058 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003059 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003060 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003061 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003062 return QualType();
3063
John McCallc1f69982010-02-02 02:21:27 +00003064 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003065 if (Method->isInstance()) {
3066 // An instance method that's referenced in a form that doesn't
3067 // look like a member pointer is just invalid.
3068 if (!R.HasFormOfMemberPointer) return QualType();
3069
Richard Smith2a7d4812013-05-04 07:00:32 +00003070 return S.Context.getMemberPointerType(Fn->getType(),
3071 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003072 }
3073
3074 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003075 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003076}
3077
3078/// Apply the deduction rules for overload sets.
3079///
3080/// \return the null type if this argument should be treated as an
3081/// undeduced context
3082static QualType
3083ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003084 Expr *Arg, QualType ParamType,
3085 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086
John McCall8d08b9b2010-08-27 09:08:28 +00003087 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003088
John McCall8d08b9b2010-08-27 09:08:28 +00003089 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003090
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003091 // C++0x [temp.deduct.call]p4
3092 unsigned TDF = 0;
3093 if (ParamWasReference)
3094 TDF |= TDF_ParamWithReferenceType;
3095 if (R.IsAddressOfOperand)
3096 TDF |= TDF_IgnoreQualifiers;
3097
John McCallc1f69982010-02-02 02:21:27 +00003098 // C++0x [temp.deduct.call]p6:
3099 // When P is a function type, pointer to function type, or pointer
3100 // to member function type:
3101
3102 if (!ParamType->isFunctionType() &&
3103 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003104 !ParamType->isMemberFunctionPointerType()) {
3105 if (Ovl->hasExplicitTemplateArgs()) {
3106 // But we can still look for an explicit specialization.
3107 if (FunctionDecl *ExplicitSpec
3108 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003109 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003110 }
John McCallc1f69982010-02-02 02:21:27 +00003111
George Burgess IVcc2f3552016-03-19 21:51:45 +00003112 DeclAccessPair DAP;
3113 if (FunctionDecl *Viable =
3114 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3115 return GetTypeOfFunction(S, R, Viable);
3116
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003117 return QualType();
3118 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003119
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003120 // Gather the explicit template arguments, if any.
3121 TemplateArgumentListInfo ExplicitTemplateArgs;
3122 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003123 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003124 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003125 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3126 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003127 NamedDecl *D = (*I)->getUnderlyingDecl();
3128
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003129 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3130 // - If the argument is an overload set containing one or more
3131 // function templates, the parameter is treated as a
3132 // non-deduced context.
3133 if (!Ovl->hasExplicitTemplateArgs())
3134 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003135
3136 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003137 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003138 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003139 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3140 Specialization, Info))
3141 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003142
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003143 D = Specialization;
3144 }
John McCallc1f69982010-02-02 02:21:27 +00003145
3146 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003147 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003148 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003149
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003150 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003152 ArgType->isFunctionType())
3153 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
John McCallc1f69982010-02-02 02:21:27 +00003155 // - If the argument is an overload set (not containing function
3156 // templates), trial argument deduction is attempted using each
3157 // of the members of the set. If deduction succeeds for only one
3158 // of the overload set members, that member is used as the
3159 // argument value for the deduction. If deduction succeeds for
3160 // more than one member of the overload set the parameter is
3161 // treated as a non-deduced context.
3162
3163 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3164 // Type deduction is done independently for each P/A pair, and
3165 // the deduced template argument values are then combined.
3166 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003167 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003168 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003169 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003170 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003171 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3172 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003173 if (Result) continue;
3174 if (!Match.isNull()) return QualType();
3175 Match = ArgType;
3176 }
3177
3178 return Match;
3179}
3180
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003182/// described in C++ [temp.deduct.call].
3183///
3184/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003185/// argument deduction based on this P/A pair because the argument is an
3186/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003187static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3188 TemplateParameterList *TemplateParams,
3189 QualType &ParamType,
3190 QualType &ArgType,
3191 Expr *Arg,
3192 unsigned &TDF) {
3193 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003194 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003195 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003196 if (ParamType.hasQualifiers())
3197 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003198
3199 // [...] If P is a reference type, the type referred to by P is
3200 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003201 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003202 if (ParamRefType)
3203 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003204
Nathan Sidwell96090022015-01-16 15:20:14 +00003205 // Overload sets usually make this parameter an undeduced context,
3206 // but there are sometimes special circumstances. Typically
3207 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003208 if (ArgType == S.Context.OverloadTy) {
3209 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3210 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003211 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003212 if (ArgType.isNull())
3213 return true;
3214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Douglas Gregor7825bf32011-01-06 22:09:01 +00003216 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003217 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003218 if (ArgType->isIncompleteArrayType()) {
3219 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003220 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003221 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003222
Douglas Gregor7825bf32011-01-06 22:09:01 +00003223 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003224 // If P is an rvalue reference to a cv-unqualified template
3225 // parameter and the argument is an lvalue, the type "lvalue
3226 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003227 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003228 !ParamType.getQualifiers() &&
3229 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003230 Arg->isLValue())
3231 ArgType = S.Context.getLValueReferenceType(ArgType);
3232 } else {
3233 // C++ [temp.deduct.call]p2:
3234 // If P is not a reference type:
3235 // - If A is an array type, the pointer type produced by the
3236 // array-to-pointer standard conversion (4.2) is used in place of
3237 // A for type deduction; otherwise,
3238 if (ArgType->isArrayType())
3239 ArgType = S.Context.getArrayDecayedType(ArgType);
3240 // - If A is a function type, the pointer type produced by the
3241 // function-to-pointer standard conversion (4.3) is used in place
3242 // of A for type deduction; otherwise,
3243 else if (ArgType->isFunctionType())
3244 ArgType = S.Context.getPointerType(ArgType);
3245 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003246 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003247 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003248 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003249 }
3250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Douglas Gregor7825bf32011-01-06 22:09:01 +00003252 // C++0x [temp.deduct.call]p4:
3253 // In general, the deduction process attempts to find template argument
3254 // values that will make the deduced A identical to A (after the type A
3255 // is transformed as described above). [...]
3256 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257
Douglas Gregor7825bf32011-01-06 22:09:01 +00003258 // - If the original P is a reference type, the deduced A (i.e., the
3259 // type referred to by the reference) can be more cv-qualified than
3260 // the transformed A.
3261 if (ParamRefType)
3262 TDF |= TDF_ParamWithReferenceType;
3263 // - The transformed A can be another pointer or pointer to member
3264 // type that can be converted to the deduced A via a qualification
3265 // conversion (4.4).
3266 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3267 ArgType->isObjCObjectPointerType())
3268 TDF |= TDF_IgnoreQualifiers;
3269 // - If P is a class and P has the form simple-template-id, then the
3270 // transformed A can be a derived class of the deduced A. Likewise,
3271 // if P is a pointer to a class of the form simple-template-id, the
3272 // transformed A can be a pointer to a derived class pointed to by
3273 // the deduced A.
3274 if (isSimpleTemplateIdType(ParamType) ||
3275 (isa<PointerType>(ParamType) &&
3276 isSimpleTemplateIdType(
3277 ParamType->getAs<PointerType>()->getPointeeType())))
3278 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279
Douglas Gregor7825bf32011-01-06 22:09:01 +00003280 return false;
3281}
3282
Nico Weberc153d242014-07-28 00:02:09 +00003283static bool
3284hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3285 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003286
Richard Smith707eab62017-01-05 04:08:31 +00003287static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Hubert Tong3280b332015-06-25 00:25:49 +00003288 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3289 Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003290 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3291 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003292 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003293
3294/// \brief Attempt template argument deduction from an initializer list
3295/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003296static Sema::TemplateDeductionResult DeduceFromInitializerList(
3297 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3298 InitListExpr *ILE, TemplateDeductionInfo &Info,
3299 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003300 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3301 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003302 // C++ [temp.deduct.call]p1: (CWG 1591)
3303 // If removing references and cv-qualifiers from P gives
3304 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3305 // a non-empty initializer list, then deduction is performed instead for
3306 // each element of the initializer list, taking P0 as a function template
3307 // parameter type and the initializer element as its argument
3308 //
Richard Smith707eab62017-01-05 04:08:31 +00003309 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003310 if (!ILE->getNumInits())
3311 return Sema::TDK_Success;
3312
Richard Smitha7d5ec92017-01-04 19:47:19 +00003313 QualType ElTy;
3314 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3315 if (ArrTy)
3316 ElTy = ArrTy->getElementType();
3317 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3318 // Otherwise, an initializer list argument causes the parameter to be
3319 // considered a non-deduced context
3320 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003321 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003322
Faisal Valif6dfdb32015-12-10 05:36:39 +00003323 // Deduction only needs to be done for dependent types.
3324 if (ElTy->isDependentType()) {
3325 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003326 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smithc92d2062017-01-05 23:02:44 +00003327 S, TemplateParams, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3328 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003329 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003330 }
3331 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003332
3333 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3334 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003335 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003336 // Determine the array bound is something we can deduce.
3337 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003338 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003339 // We can perform template argument deduction for the given non-type
3340 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003341 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3342 ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003343 if (auto Result = DeduceNonTypeTemplateArgument(
3344 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3345 /*ArrayBound=*/true, Info, Deduced))
3346 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003347 }
3348 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003349
3350 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003351}
3352
Richard Smith707eab62017-01-05 04:08:31 +00003353/// \brief Perform template argument deduction per [temp.deduct.call] for a
3354/// single parameter / argument pair.
3355static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3356 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3357 Expr *Arg, TemplateDeductionInfo &Info,
3358 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3359 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003360 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003361 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003362 QualType OrigParamType = ParamType;
3363
3364 // If P is a reference type [...]
3365 // If P is a cv-qualified type [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003366 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith363ae812017-01-04 22:03:59 +00003367 ArgType, Arg, TDF))
3368 return Sema::TDK_Success;
3369
Richard Smith707eab62017-01-05 04:08:31 +00003370 // If [...] the argument is a non-empty initializer list [...]
3371 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3372 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003373 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003374
3375 // [...] the deduction process attempts to find template argument values
3376 // that will make the deduced A identical to A
3377 //
3378 // Keep track of the argument type and corresponding parameter index,
3379 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003380 OriginalCallArgs.push_back(
3381 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003382 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003383 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003384}
3385
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003386/// \brief Perform template argument deduction from a function call
3387/// (C++ [temp.deduct.call]).
3388///
3389/// \param FunctionTemplate the function template for which we are performing
3390/// template argument deduction.
3391///
James Dennett18348b62012-06-22 08:52:37 +00003392/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003393/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003394///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003395/// \param Args the function call arguments
3396///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003397/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003398/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003399/// template argument deduction.
3400///
3401/// \param Info the argument will be updated to provide additional information
3402/// about template argument deduction.
3403///
Richard Smith6eedfe72017-01-09 08:01:21 +00003404/// \param CheckNonDependent A callback to invoke to check conversions for
3405/// non-dependent parameters, between deduction and substitution, per DR1391.
3406/// If this returns true, substitution will be skipped and we return
3407/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3408/// types (after substituting explicit template arguments).
3409///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003410/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003411Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3412 FunctionTemplateDecl *FunctionTemplate,
3413 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003414 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003415 bool PartialOverloading,
3416 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003417 if (FunctionTemplate->isInvalidDecl())
3418 return TDK_Invalid;
3419
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003420 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003421 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003422
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003423 // C++ [temp.deduct.call]p1:
3424 // Template argument deduction is done by comparing each function template
3425 // parameter type (call it P) with the type of the corresponding argument
3426 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003427 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003428 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003429 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003430 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003431 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003432 if (Proto->isTemplateVariadic())
3433 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003434 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003435 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003436 }
Mike Stump11289f42009-09-09 15:08:12 +00003437
Douglas Gregor89026b52009-06-30 23:57:56 +00003438 // The types of the parameters from which we will perform template argument
3439 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003440 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003441 TemplateParameterList *TemplateParams
3442 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003443 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003444 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003445 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003446 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003447 TemplateDeductionResult Result =
3448 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003449 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003450 Deduced,
3451 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003452 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003453 Info);
3454 if (Result)
3455 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003456
3457 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003458 } else {
3459 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003460 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003461 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3462 }
Mike Stump11289f42009-09-09 15:08:12 +00003463
Richard Smith6eedfe72017-01-09 08:01:21 +00003464 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003465
3466 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3467 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003468 // C++ [demp.deduct.call]p1: (DR1391)
3469 // Template argument deduction is done by comparing each function template
3470 // parameter that contains template-parameters that participate in
3471 // template argument deduction ...
Richard Smitha7d5ec92017-01-04 19:47:19 +00003472 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3473 return Sema::TDK_Success;
3474
Richard Smith707eab62017-01-05 04:08:31 +00003475 // ... with the type of the corresponding argument
3476 return DeduceTemplateArgumentsFromCallArgument(
3477 *this, TemplateParams, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003478 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003479 };
3480
Douglas Gregor89026b52009-06-30 23:57:56 +00003481 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003482 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003483 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003484 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003485 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003486 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003487
Richard Smitha7d5ec92017-01-04 19:47:19 +00003488 const PackExpansionType *ParamExpansion =
3489 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003490 if (!ParamExpansion) {
3491 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003492 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003493 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Richard Smith6eedfe72017-01-09 08:01:21 +00003495 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003496 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003497 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003498
Douglas Gregor7825bf32011-01-06 22:09:01 +00003499 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Richard Smithde0d34a2017-01-09 07:14:40 +00003502 QualType ParamPattern = ParamExpansion->getPattern();
3503 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3504 ParamPattern);
3505
Douglas Gregor7825bf32011-01-06 22:09:01 +00003506 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507 // For a function parameter pack that occurs at the end of the
3508 // parameter-declaration-list, the type A of each remaining argument of
3509 // the call is compared with the type P of the declarator-id of the
3510 // function parameter pack. Each comparison deduces template arguments
3511 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003512 // the function parameter pack. When a function parameter pack appears
3513 // in a non-deduced context [not at the end of the list], the type of
3514 // that parameter pack is never deduced.
3515 //
3516 // FIXME: The above rule allows the size of the parameter pack to change
3517 // after we skip it (in the non-deduced case). That makes no sense, so
3518 // we instead notionally deduce the pack against N arguments, where N is
3519 // the length of the explicitly-specified pack if it's expanded by the
3520 // parameter pack and 0 otherwise, and we treat each deduction as a
3521 // non-deduced context.
3522 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003523 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3524 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003525 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3526 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003527 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003528 } else {
3529 // If the parameter type contains an explicitly-specified pack that we
3530 // could not expand, skip the number of parameters notionally created
3531 // by the expansion.
3532 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003533 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003534 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003535 ++I, ++ArgIdx) {
3536 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003537 // FIXME: Should we add OriginalCallArgs for these? What if the
3538 // corresponding argument is a list?
3539 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003540 }
3541 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
Douglas Gregor7825bf32011-01-06 22:09:01 +00003544 // Build argument packs for each of the parameter packs expanded by this
3545 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003546 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003548 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003549
Richard Smith6eedfe72017-01-09 08:01:21 +00003550 return FinishTemplateArgumentDeduction(
3551 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3552 &OriginalCallArgs, PartialOverloading,
3553 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003554}
3555
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003556QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003557 QualType FunctionType,
3558 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003559 if (ArgFunctionType.isNull())
3560 return ArgFunctionType;
3561
3562 const FunctionProtoType *FunctionTypeP =
3563 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003564 const FunctionProtoType *ArgFunctionTypeP =
3565 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003566
3567 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3568 bool Rebuild = false;
3569
3570 CallingConv CC = FunctionTypeP->getCallConv();
3571 if (EPI.ExtInfo.getCC() != CC) {
3572 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3573 Rebuild = true;
3574 }
3575
3576 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3577 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3578 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3579 Rebuild = true;
3580 }
3581
3582 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3583 ArgFunctionTypeP->hasExceptionSpec())) {
3584 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3585 Rebuild = true;
3586 }
3587
3588 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003589 return ArgFunctionType;
3590
Richard Smithbaa47832016-12-01 02:11:49 +00003591 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3592 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003593}
3594
Douglas Gregor9b146582009-07-08 20:55:45 +00003595/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003596/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3597/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003598///
3599/// \param FunctionTemplate the function template for which we are performing
3600/// template argument deduction.
3601///
James Dennett18348b62012-06-22 08:52:37 +00003602/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003603/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003604///
3605/// \param ArgFunctionType the function type that will be used as the
3606/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003607/// function template's function type. This type may be NULL, if there is no
3608/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003609///
3610/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003611/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003612/// template argument deduction.
3613///
3614/// \param Info the argument will be updated to provide additional information
3615/// about template argument deduction.
3616///
Richard Smithbaa47832016-12-01 02:11:49 +00003617/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3618/// the address of a function template per [temp.deduct.funcaddr] and
3619/// [over.over]. If \c false, we are looking up a function template
3620/// specialization based on its signature, per [temp.deduct.decl].
3621///
Douglas Gregor9b146582009-07-08 20:55:45 +00003622/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003623Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3624 FunctionTemplateDecl *FunctionTemplate,
3625 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3626 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3627 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003628 if (FunctionTemplate->isInvalidDecl())
3629 return TDK_Invalid;
3630
Douglas Gregor9b146582009-07-08 20:55:45 +00003631 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3632 TemplateParameterList *TemplateParams
3633 = FunctionTemplate->getTemplateParameters();
3634 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003635
3636 // When taking the address of a function, we require convertibility of
3637 // the resulting function type. Otherwise, we allow arbitrary mismatches
3638 // of calling convention, noreturn, and noexcept.
3639 if (!IsAddressOfFunction)
3640 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3641 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregor9b146582009-07-08 20:55:45 +00003643 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003644 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003645 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003646 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003647 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003648 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003649 if (TemplateDeductionResult Result
3650 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003651 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003652 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003653 &FunctionType, Info))
3654 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003655
3656 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003657 }
3658
Eli Friedman77dcc722012-02-08 03:07:05 +00003659 // Unevaluated SFINAE context.
3660 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003661 SFINAETrap Trap(*this);
3662
John McCallc1f69982010-02-02 02:21:27 +00003663 Deduced.resize(TemplateParams->size());
3664
Richard Smith2a7d4812013-05-04 07:00:32 +00003665 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003666 // type so that we treat it as a non-deduced context in what follows. If we
3667 // are looking up by signature, the signature type should also have a deduced
3668 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003669 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003670 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003671 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003672 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003673 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003674 }
3675
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003676 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003677 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003678 if (IsAddressOfFunction)
3679 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003680 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003681 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003682 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003683 FunctionType, ArgFunctionType,
3684 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003685 return Result;
3686 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003687
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003689 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3690 NumExplicitlySpecified,
3691 Specialization, Info))
3692 return Result;
3693
Richard Smith2a7d4812013-05-04 07:00:32 +00003694 // If the function has a deduced return type, deduce it now, so we can check
3695 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003696 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003697 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003698 DeduceReturnType(Specialization, Info.getLocation(), false))
3699 return TDK_MiscellaneousDeductionFailure;
3700
Richard Smith9095e5b2016-11-01 01:31:23 +00003701 // If the function has a dependent exception specification, resolve it now,
3702 // so we can check that the exception specification matches.
3703 auto *SpecializationFPT =
3704 Specialization->getType()->castAs<FunctionProtoType>();
3705 if (getLangOpts().CPlusPlus1z &&
3706 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3707 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3708 return TDK_MiscellaneousDeductionFailure;
3709
Richard Smithbaa47832016-12-01 02:11:49 +00003710 // Adjust the exception specification of the argument again to match the
3711 // substituted and resolved type we just formed. (Calling convention and
3712 // noreturn can't be dependent, so we don't actually need this for them
3713 // right now.)
3714 QualType SpecializationType = Specialization->getType();
3715 if (!IsAddressOfFunction)
3716 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3717 /*AdjustExceptionSpec*/true);
3718
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003719 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003720 // specialization with respect to arguments of compatible pointer to function
3721 // types, template argument deduction fails.
3722 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003723 if (IsAddressOfFunction &&
3724 !isSameOrCompatibleFunctionType(
3725 Context.getCanonicalType(SpecializationType),
3726 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003727 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003728
3729 if (!IsAddressOfFunction &&
3730 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003731 return TDK_MiscellaneousDeductionFailure;
3732 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003733
3734 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003735}
3736
Simon Pilgrim728134c2016-08-12 11:43:57 +00003737/// \brief Given a function declaration (e.g. a generic lambda conversion
3738/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003739/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3740/// to replace 'auto' with and not the actual result type you want
3741/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003742static inline void
3743SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003744 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003745 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003746 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003747 assert(AutoResultType->getContainedAutoType());
3748 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003749 TypeToReplaceAutoWith);
3750 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3751}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003752
Simon Pilgrim728134c2016-08-12 11:43:57 +00003753/// \brief Given a specialized conversion operator of a generic lambda
3754/// create the corresponding specializations of the call operator and
3755/// the static-invoker. If the return type of the call operator is auto,
3756/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003757/// return type of the destination function ptr.
3758
Simon Pilgrim728134c2016-08-12 11:43:57 +00003759static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003760SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3761 CXXConversionDecl *ConversionSpecialized,
3762 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3763 QualType ReturnTypeOfDestFunctionPtr,
3764 TemplateDeductionInfo &TDInfo,
3765 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003766
Faisal Vali2b3a3012013-10-24 23:40:02 +00003767 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003768 assert(LambdaClass && LambdaClass->isGenericLambda());
3769
Faisal Vali2b3a3012013-10-24 23:40:02 +00003770 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003771 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003772 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003773 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003774
3775 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 CallOpGeneric->getDescribedFunctionTemplate();
3777
Craig Topperc3ec1492014-05-26 06:22:03 +00003778 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003779 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003780 // generic lambda's call operator.
3781 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003782 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3783 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003784 0, CallOpSpecialized, TDInfo))
3785 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003786
Faisal Vali2b3a3012013-10-24 23:40:02 +00003787 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003788 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3789 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003790 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003791 CallOpSpecialized->getPointOfInstantiation(),
3792 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003793
Faisal Vali2b3a3012013-10-24 23:40:02 +00003794 // Check to see if the return type of the destination ptr-to-function
3795 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003796 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003797 ReturnTypeOfDestFunctionPtr))
3798 return Sema::TDK_NonDeducedMismatch;
3799 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003800 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003801 // specialized our corresponding call operator, we are ready to
3802 // specialize the static invoker with the deduced arguments of our
3803 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003804 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003805 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3806 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3807
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003808#ifndef NDEBUG
3809 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3810#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003811 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003812 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003813 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003814 "If the call operator succeeded so should the invoker!");
3815 // Set the result type to match the corresponding call operator
3816 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003817 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3818 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003819 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003820 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003821 // to substitute into the 'auto' of the invoker and conversion
3822 // function.
3823 // For e.g.
3824 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3825 // We don't want to subst 'int*' into 'auto' to get int**.
3826
Alp Toker314cc812014-01-25 16:55:45 +00003827 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3828 ->getContainedAutoType()
3829 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003830 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3831 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003832 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003833 TypeToReplaceAutoWith, S);
3834 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003835
Faisal Vali2b3a3012013-10-24 23:40:02 +00003836 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003837 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003838 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003839 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003840 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3841 getType().getTypePtr()->castAs<FunctionProtoType>();
3842 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3843 EPI.TypeQuals = 0;
3844 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003845 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003846 return Sema::TDK_Success;
3847}
Douglas Gregor05155d82009-08-21 23:19:43 +00003848/// \brief Deduce template arguments for a templated conversion
3849/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3850/// conversion function template specialization.
3851Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003852Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003853 QualType ToType,
3854 CXXConversionDecl *&Specialization,
3855 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003856 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003857 return TDK_Invalid;
3858
Faisal Vali2b3a3012013-10-24 23:40:02 +00003859 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003860 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3861
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003863
3864 // Canonicalize the types for deduction.
3865 QualType P = Context.getCanonicalType(FromType);
3866 QualType A = Context.getCanonicalType(ToType);
3867
Douglas Gregord99609a2011-03-06 09:03:20 +00003868 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003869 // If P is a reference type, the type referred to by P is used for
3870 // type deduction.
3871 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3872 P = PRef->getPointeeType();
3873
Douglas Gregord99609a2011-03-06 09:03:20 +00003874 // C++0x [temp.deduct.conv]p4:
3875 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003876 // for type deduction.
3877 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003878 A = ARef->getPointeeType().getUnqualifiedType();
3879 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003880 //
Mike Stump11289f42009-09-09 15:08:12 +00003881 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003882 else {
3883 assert(!A->isReferenceType() && "Reference types were handled above");
3884
3885 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003886 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003887 // of P for type deduction; otherwise,
3888 if (P->isArrayType())
3889 P = Context.getArrayDecayedType(P);
3890 // - If P is a function type, the pointer type produced by the
3891 // function-to-pointer standard conversion (4.3) is used in
3892 // place of P for type deduction; otherwise,
3893 else if (P->isFunctionType())
3894 P = Context.getPointerType(P);
3895 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003896 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003897 else
3898 P = P.getUnqualifiedType();
3899
Douglas Gregord99609a2011-03-06 09:03:20 +00003900 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003901 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003902 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003903 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003904 A = A.getUnqualifiedType();
3905 }
3906
Eli Friedman77dcc722012-02-08 03:07:05 +00003907 // Unevaluated SFINAE context.
3908 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003909 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003910
3911 // C++ [temp.deduct.conv]p1:
3912 // Template argument deduction is done by comparing the return
3913 // type of the template conversion function (call it P) with the
3914 // type that is required as the result of the conversion (call it
3915 // A) as described in 14.8.2.4.
3916 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003917 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003918 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003919 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003920
3921 // C++0x [temp.deduct.conv]p4:
3922 // In general, the deduction process attempts to find template
3923 // argument values that will make the deduced A identical to
3924 // A. However, there are two cases that allow a difference:
3925 unsigned TDF = 0;
3926 // - If the original A is a reference type, A can be more
3927 // cv-qualified than the deduced A (i.e., the type referred to
3928 // by the reference)
3929 if (ToType->isReferenceType())
3930 TDF |= TDF_ParamWithReferenceType;
3931 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003932 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003933 // conversion.
3934 //
3935 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3936 // both P and A are pointers or member pointers. In this case, we
3937 // just ignore cv-qualifiers completely).
3938 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003939 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003940 TDF |= TDF_IgnoreQualifiers;
3941 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003942 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3943 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003944 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003945
3946 // Create an Instantiation Scope for finalizing the operator.
3947 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003948 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003949 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003950 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003951 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003952 ConversionSpecialized, Info);
3953 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3954
3955 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003956 // to a ptr-to-function, use the deduced arguments from the conversion
3957 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003958 // e.g., int (*fp)(int) = [](auto a) { return a; };
3959 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003960
Faisal Vali2b3a3012013-10-24 23:40:02 +00003961 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003962 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003963 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003964 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003965 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003966 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003967 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003968 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3969
Simon Pilgrim728134c2016-08-12 11:43:57 +00003970 // Create the corresponding specializations of the call operator and
3971 // the static-invoker; and if the return type is auto,
3972 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003973 // DestFunctionPtrReturnType.
3974 // For instance:
3975 // auto L = [](auto a) { return f(a); };
3976 // int (*fp)(int) = L;
3977 // char (*fp2)(int) = L; <-- Not OK.
3978
3979 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003980 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003981 Info, *this);
3982 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003983 return Result;
3984}
3985
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003986/// \brief Deduce template arguments for a function template when there is
3987/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3988///
3989/// \param FunctionTemplate the function template for which we are performing
3990/// template argument deduction.
3991///
James Dennett18348b62012-06-22 08:52:37 +00003992/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003993/// arguments.
3994///
3995/// \param Specialization if template argument deduction was successful,
3996/// this will be set to the function template specialization produced by
3997/// template argument deduction.
3998///
3999/// \param Info the argument will be updated to provide additional information
4000/// about template argument deduction.
4001///
Richard Smithbaa47832016-12-01 02:11:49 +00004002/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4003/// the address of a function template in a context where we do not have a
4004/// target type, per [over.over]. If \c false, we are looking up a function
4005/// template specialization based on its signature, which only happens when
4006/// deducing a function parameter type from an argument that is a template-id
4007/// naming a function template specialization.
4008///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004009/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004010Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4011 FunctionTemplateDecl *FunctionTemplate,
4012 TemplateArgumentListInfo *ExplicitTemplateArgs,
4013 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4014 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004015 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004016 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004017 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004018}
4019
Richard Smith30482bc2011-02-20 03:19:35 +00004020namespace {
4021 /// Substitute the 'auto' type specifier within a type for a given replacement
4022 /// type.
4023 class SubstituteAutoTransform :
4024 public TreeTransform<SubstituteAutoTransform> {
4025 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00004026 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004027 public:
Richard Smith87d263e2016-12-25 08:05:23 +00004028 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
4029 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00004030 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00004031 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00004032
Richard Smith30482bc2011-02-20 03:19:35 +00004033 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4034 // If we're building the type pattern to deduce against, don't wrap the
4035 // substituted type in an AutoType. Certain template deduction rules
4036 // apply only when a template type parameter appears directly (and not if
4037 // the parameter is found through desugaring). For instance:
4038 // auto &&lref = lvalue;
4039 // must transform into "rvalue reference to T" not "rvalue reference to
4040 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00004041 if (!UseAutoSugar) {
4042 assert(isa<TemplateTypeParmType>(Replacement) &&
4043 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00004044 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00004045 TemplateTypeParmTypeLoc NewTL =
4046 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00004047 NewTL.setNameLoc(TL.getNameLoc());
4048 return Result;
4049 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00004050 QualType Result = SemaRef.Context.getAutoType(
4051 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00004052 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4053 NewTL.setNameLoc(TL.getNameLoc());
4054 return Result;
4055 }
4056 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004057
4058 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4059 // Lambdas never need to be transformed.
4060 return E;
4061 }
Richard Smith061f1e22013-04-30 21:23:01 +00004062
Richard Smith2a7d4812013-05-04 07:00:32 +00004063 QualType Apply(TypeLoc TL) {
4064 // Create some scratch storage for the transformed type locations.
4065 // FIXME: We're just going to throw this information away. Don't build it.
4066 TypeLocBuilder TLB;
4067 TLB.reserve(TL.getFullDataSize());
4068 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004069 }
Richard Smith30482bc2011-02-20 03:19:35 +00004070 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004071}
Richard Smith30482bc2011-02-20 03:19:35 +00004072
Richard Smith2a7d4812013-05-04 07:00:32 +00004073Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004074Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4075 Optional<unsigned> DependentDeductionDepth) {
4076 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4077 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004078}
4079
Richard Smith061f1e22013-04-30 21:23:01 +00004080/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004081///
Richard Smith87d263e2016-12-25 08:05:23 +00004082/// Note that this is done even if the initializer is dependent. (This is
4083/// necessary to support partial ordering of templates using 'auto'.)
4084/// A dependent type will be produced when deducing from a dependent type.
4085///
Richard Smith30482bc2011-02-20 03:19:35 +00004086/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004087/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004088/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004089/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004090/// \param DependentDeductionDepth Set if we should permit deduction in
4091/// dependent cases. This is necessary for template partial ordering with
4092/// 'auto' template parameters. The value specified is the template
4093/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004094Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004095Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4096 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004097 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004098 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4099 if (NonPlaceholder.isInvalid())
4100 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004101 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004102 }
4103
Richard Smith87d263e2016-12-25 08:05:23 +00004104 if (!DependentDeductionDepth &&
4105 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4106 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004107 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004108 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004109 }
4110
Richard Smith87d263e2016-12-25 08:05:23 +00004111 // Find the depth of template parameter to synthesize.
4112 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4113
Richard Smith74aeef52013-04-26 16:15:35 +00004114 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4115 // Since 'decltype(auto)' can only occur at the top of the type, we
4116 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004117 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004118 if (AT->isDecltypeAuto()) {
4119 if (isa<InitListExpr>(Init)) {
4120 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4121 return DAR_FailedAlreadyDiagnosed;
4122 }
4123
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004124 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004125 if (Deduced.isNull())
4126 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004127 // FIXME: Support a non-canonical deduced type for 'auto'.
4128 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004129 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004130 if (Result.isNull())
4131 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004132 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004133 } else if (!getLangOpts().CPlusPlus) {
4134 if (isa<InitListExpr>(Init)) {
4135 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4136 return DAR_FailedAlreadyDiagnosed;
4137 }
Richard Smith74aeef52013-04-26 16:15:35 +00004138 }
4139 }
4140
Richard Smith30482bc2011-02-20 03:19:35 +00004141 SourceLocation Loc = Init->getExprLoc();
4142
4143 LocalInstantiationScope InstScope(*this);
4144
4145 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004146 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4147 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004148 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4149 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004150 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4151 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004152
Richard Smith87d263e2016-12-25 08:05:23 +00004153 QualType FuncParam =
4154 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4155 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004156 assert(!FuncParam.isNull() &&
4157 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004158
4159 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004160 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004161 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004162
Richard Smith87d263e2016-12-25 08:05:23 +00004163 TemplateDeductionInfo Info(Loc, Depth);
4164
4165 // If deduction failed, don't diagnose if the initializer is dependent; it
4166 // might acquire a matching type in the instantiation.
4167 auto DeductionFailed = [&]() -> DeduceAutoResult {
4168 if (Init->isTypeDependent()) {
4169 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4170 assert(!Result.isNull() && "substituting DependentTy can't fail");
4171 return DAR_Succeeded;
4172 }
4173 return DAR_Failed;
4174 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004175
Richard Smith707eab62017-01-05 04:08:31 +00004176 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4177
Richard Smith74801c82012-07-08 04:13:07 +00004178 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004179 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004180 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4181 // against that. Such deduction only succeeds if removing cv-qualifiers and
4182 // references results in std::initializer_list<T>.
4183 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4184 return DAR_Failed;
4185
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004186 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004187 if (DeduceTemplateArgumentsFromCallArgument(
4188 *this, TemplateParamsSt.get(), TemplArg, InitList->getInit(i),
Richard Smithc92d2062017-01-05 23:02:44 +00004189 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4190 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004191 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004192 }
4193 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004194 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4195 Diag(Loc, diag::err_auto_bitfield);
4196 return DAR_FailedAlreadyDiagnosed;
4197 }
4198
Richard Smith707eab62017-01-05 04:08:31 +00004199 if (DeduceTemplateArgumentsFromCallArgument(
4200 *this, TemplateParamsSt.get(), FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004201 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004202 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004203 }
Richard Smith30482bc2011-02-20 03:19:35 +00004204
Richard Smith87d263e2016-12-25 08:05:23 +00004205 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004206 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004207 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004208
Eli Friedmane4310952012-11-06 23:56:42 +00004209 QualType DeducedType = Deduced[0].getAsType();
4210
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004211 if (InitList) {
4212 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4213 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004214 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004215 }
4216
Richard Smith061f1e22013-04-30 21:23:01 +00004217 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004218 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004219 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004220
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004221 // Check that the deduced argument type is compatible with the original
4222 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004223 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004224 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004225 assert((bool)InitList == OriginalArg.DecomposedParam &&
4226 "decomposed non-init-list in auto deduction?");
4227 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004228 Result = QualType();
4229 return DeductionFailed();
4230 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004231 }
4232
Sebastian Redl09edce02012-01-23 22:09:39 +00004233 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004234}
4235
Simon Pilgrim728134c2016-08-12 11:43:57 +00004236QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004237 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004238 if (TypeToReplaceAuto->isDependentType())
4239 TypeToReplaceAuto = QualType();
4240 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4241 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004242}
4243
Simon Pilgrim728134c2016-08-12 11:43:57 +00004244TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004245 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004246 if (TypeToReplaceAuto->isDependentType())
4247 TypeToReplaceAuto = QualType();
4248 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4249 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004250}
4251
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004252void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4253 if (isa<InitListExpr>(Init))
4254 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004255 VDecl->isInitCapture()
4256 ? diag::err_init_capture_deduction_failure_from_init_list
4257 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004258 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4259 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004260 Diag(VDecl->getLocation(),
4261 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4262 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004263 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4264 << Init->getSourceRange();
4265}
4266
Richard Smith2a7d4812013-05-04 07:00:32 +00004267bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4268 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004269 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004270
4271 if (FD->getTemplateInstantiationPattern())
4272 InstantiateFunctionDefinition(Loc, FD);
4273
Alp Toker314cc812014-01-25 16:55:45 +00004274 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004275 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4276 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4277 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4278 }
4279
4280 return StillUndeduced;
4281}
4282
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004284static void
4285AddImplicitObjectParameterType(ASTContext &Context,
4286 CXXMethodDecl *Method,
4287 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004288 // C++11 [temp.func.order]p3:
4289 // [...] The 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.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004292 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004293 // The standard doesn't say explicitly, but we pick the appropriate kind of
4294 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004295 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4296 ArgTy = Context.getQualifiedType(ArgTy,
4297 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004298 if (Method->getRefQualifier() == RQ_RValue)
4299 ArgTy = Context.getRValueReferenceType(ArgTy);
4300 else
4301 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004302 ArgTypes.push_back(ArgTy);
4303}
4304
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004305/// \brief Determine whether the function template \p FT1 is at least as
4306/// specialized as \p FT2.
4307static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004308 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004309 FunctionTemplateDecl *FT1,
4310 FunctionTemplateDecl *FT2,
4311 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004312 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004313 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004315 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4316 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004318 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4319 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004320 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004321 Deduced.resize(TemplateParams->size());
4322
4323 // C++0x [temp.deduct.partial]p3:
4324 // The types used to determine the ordering depend on the context in which
4325 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004326 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004327 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004328 switch (TPOC) {
4329 case TPOC_Call: {
4330 // - In the context of a function call, the function parameter types are
4331 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004332 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4333 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004334
Eli Friedman3b5774a2012-09-19 23:27:04 +00004335 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004336 // [...] If only one of the function templates is a non-static
4337 // member, that function template is considered to have a new
4338 // first parameter inserted in its function parameter list. The
4339 // new parameter is of type "reference to cv A," where cv are
4340 // the cv-qualifiers of the function template (if any) and A is
4341 // the class of which the function template is a member.
4342 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004343 // Note that we interpret this to mean "if one of the function
4344 // templates is a non-static member and the other is a non-member";
4345 // otherwise, the ordering rules for static functions against non-static
4346 // functions don't make any sense.
4347 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004348 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4349 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004350 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004351
Richard Smithe5b52202013-09-11 00:52:39 +00004352 unsigned NumComparedArguments = NumCallArguments1;
4353
4354 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004355 // Compare 'this' from Method1 against first parameter from Method2.
4356 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4357 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004358 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004359 // Compare 'this' from Method2 against first parameter from Method1.
4360 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004361 }
4362
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004363 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004364 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004365 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004366 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregorb837ea42011-01-11 17:34:58 +00004368 // C++ [temp.func.order]p5:
4369 // The presence of unused ellipsis and default arguments has no effect on
4370 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004371 if (Args1.size() > NumComparedArguments)
4372 Args1.resize(NumComparedArguments);
4373 if (Args2.size() > NumComparedArguments)
4374 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004375 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4376 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004377 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004378 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004380 break;
4381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004382
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383 case TPOC_Conversion:
4384 // - In the context of a call to a conversion operator, the return types
4385 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004386 if (DeduceTemplateArgumentsByTypeMatch(
4387 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4388 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004389 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004390 return false;
4391 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004393 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004394 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004395 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004396 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4397 FD2->getType(), FD1->getType(),
4398 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004399 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004400 return false;
4401 break;
4402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004404 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405 // In most cases, all template parameters must have values in order for
4406 // deduction to succeed, but for partial ordering purposes a template
4407 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004408 // types being used for partial ordering. [ Note: a template parameter used
4409 // in a non-deduced context is considered used. -end note]
4410 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4411 for (; ArgIdx != NumArgs; ++ArgIdx)
4412 if (Deduced[ArgIdx].isNull())
4413 break;
4414
Richard Smithcf824862016-12-30 04:32:02 +00004415 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4416 // to substitute the deduced arguments back into the template and check that
4417 // we get the right type.
4418
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004419 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004421 // as FT2.
4422 return true;
4423 }
4424
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004425 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004426 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004427 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004428 case TPOC_Call:
4429 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4430 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004431 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004432 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004433 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004435 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004436 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4437 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004438 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004440 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004441 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004442 TemplateParams->getDepth(),
4443 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004444 break;
4445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004447 for (; ArgIdx != NumArgs; ++ArgIdx)
4448 // If this argument had no value deduced but was used in one of the types
4449 // used for partial ordering, then deduction fails.
4450 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4451 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004453 return true;
4454}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455
Douglas Gregorcef1a032011-01-16 16:03:23 +00004456/// \brief Determine whether this a function template whose parameter-type-list
4457/// ends with a function parameter pack.
4458static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4459 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4460 unsigned NumParams = Function->getNumParams();
4461 if (NumParams == 0)
4462 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
Douglas Gregorcef1a032011-01-16 16:03:23 +00004464 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4465 if (!Last->isParameterPack())
4466 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Douglas Gregorcef1a032011-01-16 16:03:23 +00004468 // Make sure that no previous parameter is a parameter pack.
4469 while (--NumParams > 0) {
4470 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4471 return false;
4472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Douglas Gregorcef1a032011-01-16 16:03:23 +00004474 return true;
4475}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Douglas Gregorbe999392009-09-15 16:23:51 +00004477/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004478/// to the rules of function template partial ordering (C++ [temp.func.order]).
4479///
4480/// \param FT1 the first function template
4481///
4482/// \param FT2 the second function template
4483///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004484/// \param TPOC the context in which we are performing partial ordering of
4485/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004486///
Richard Smithe5b52202013-09-11 00:52:39 +00004487/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4488/// only when \c TPOC is \c TPOC_Call.
4489///
4490/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4491/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004492///
Douglas Gregorbe999392009-09-15 16:23:51 +00004493/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004494/// template is more specialized, returns NULL.
4495FunctionTemplateDecl *
4496Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4497 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004498 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004499 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004500 unsigned NumCallArguments1,
4501 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004503 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004505 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004507 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004508 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004510 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004511 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004512
Douglas Gregorcef1a032011-01-16 16:03:23 +00004513 // FIXME: This mimics what GCC implements, but doesn't match up with the
4514 // proposed resolution for core issue 692. This area needs to be sorted out,
4515 // but for now we attempt to maintain compatibility.
4516 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4517 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4518 if (Variadic1 != Variadic2)
4519 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Craig Topperc3ec1492014-05-26 06:22:03 +00004521 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004522}
Douglas Gregor9b146582009-07-08 20:55:45 +00004523
Douglas Gregor450f00842009-09-25 18:43:00 +00004524/// \brief Determine if the two templates are equivalent.
4525static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4526 if (T1 == T2)
4527 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528
Douglas Gregor450f00842009-09-25 18:43:00 +00004529 if (!T1 || !T2)
4530 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4533}
4534
4535/// \brief Retrieve the most specialized of the given function template
4536/// specializations.
4537///
John McCall58cc69d2010-01-27 01:50:18 +00004538/// \param SpecBegin the start iterator of the function template
4539/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004540///
John McCall58cc69d2010-01-27 01:50:18 +00004541/// \param SpecEnd the end iterator of the function template
4542/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004543///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004545/// diagnostic should occur.
4546///
4547/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4548/// no matching candidates.
4549///
4550/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4551/// occurs.
4552///
4553/// \param CandidateDiag partial diagnostic used for each function template
4554/// specialization that is a candidate in the ambiguous ordering. One parameter
4555/// in this diagnostic should be unbound, which will correspond to the string
4556/// describing the template arguments for the function template specialization.
4557///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004559/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004560UnresolvedSetIterator Sema::getMostSpecialized(
4561 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4562 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004563 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4564 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4565 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004566 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004567 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004568 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004569 FailedCandidates.NoteCandidates(*this, Loc);
4570 }
John McCall58cc69d2010-01-27 01:50:18 +00004571 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573
4574 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004575 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Douglas Gregor450f00842009-09-25 18:43:00 +00004577 // Find the function template that is better than all of the templates it
4578 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004579 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004581 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004582 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004583 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4584 FunctionTemplateDecl *Challenger
4585 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004586 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004587 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004588 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004589 Challenger)) {
4590 Best = I;
4591 BestTemplate = Challenger;
4592 }
4593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
Douglas Gregor450f00842009-09-25 18:43:00 +00004595 // Make sure that the "best" function template is more specialized than all
4596 // of the others.
4597 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004598 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4599 FunctionTemplateDecl *Challenger
4600 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004601 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004603 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004604 BestTemplate)) {
4605 Ambiguous = true;
4606 break;
4607 }
4608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor450f00842009-09-25 18:43:00 +00004610 if (!Ambiguous) {
4611 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004612 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Douglas Gregor450f00842009-09-25 18:43:00 +00004615 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004616 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004617 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Richard Smithb875c432013-05-04 01:51:08 +00004619 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004620 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4621 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004622 const auto *FD = cast<FunctionDecl>(*I);
4623 PD << FD << getTemplateArgumentBindingsText(
4624 FD->getPrimaryTemplate()->getTemplateParameters(),
4625 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004626 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004627 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004628 Diag((*I)->getLocation(), PD);
4629 }
Richard Smithb875c432013-05-04 01:51:08 +00004630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004631
John McCall58cc69d2010-01-27 01:50:18 +00004632 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004633}
4634
Richard Smith0da6dc42016-12-24 16:40:51 +00004635/// Determine whether one partial specialization, P1, is at least as
4636/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004637///
Richard Smith26b86ea2016-12-31 21:41:23 +00004638/// \tparam TemplateLikeDecl The kind of P2, which must be a
4639/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004640/// \param T1 The injected-class-name of P1 (faked for a variable template).
4641/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004642template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004643static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004644 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004645 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004646 // C++ [temp.class.order]p1:
4647 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648 // specialized as the second if, given the following rewrite to two
4649 // function templates, the first function template is at least as
4650 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004651 // templates (14.6.6.2):
4652 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653 // first partial specialization and has a single function parameter
4654 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004655 // arguments of the first partial specialization, and
4656 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657 // second partial specialization and has a single function parameter
4658 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004659 // arguments of the second partial specialization.
4660 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004661 // Rather than synthesize function templates, we merely perform the
4662 // equivalent partial ordering by performing deduction directly on
4663 // the template arguments of the class template partial
4664 // specializations. This computation is slightly simpler than the
4665 // general problem of function template partial ordering, because
4666 // class template partial specializations are more constrained. We
4667 // know that every template parameter is deducible from the class
4668 // template partial specialization's template arguments, for
4669 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004670 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004671
Richard Smith0da6dc42016-12-24 16:40:51 +00004672 // Determine whether P1 is at least as specialized as P2.
4673 Deduced.resize(P2->getTemplateParameters()->size());
4674 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4675 T2, T1, Info, Deduced, TDF_None,
4676 /*PartialOrdering=*/true))
4677 return false;
4678
4679 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4680 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004681 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4682 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004683 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4684 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004685 S, P2, /*PartialOrdering=*/true,
4686 TemplateArgumentList(TemplateArgumentList::OnStack,
4687 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004688 Deduced, Info))
4689 return false;
4690
4691 return true;
4692}
4693
4694/// \brief Returns the more specialized class template partial specialization
4695/// according to the rules of partial ordering of class template partial
4696/// specializations (C++ [temp.class.order]).
4697///
4698/// \param PS1 the first class template partial specialization
4699///
4700/// \param PS2 the second class template partial specialization
4701///
4702/// \returns the more specialized class template partial specialization. If
4703/// neither partial specialization is more specialized, returns NULL.
4704ClassTemplatePartialSpecializationDecl *
4705Sema::getMoreSpecializedPartialSpecialization(
4706 ClassTemplatePartialSpecializationDecl *PS1,
4707 ClassTemplatePartialSpecializationDecl *PS2,
4708 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004709 QualType PT1 = PS1->getInjectedSpecializationType();
4710 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
Richard Smith0e617ec2016-12-27 07:56:27 +00004712 TemplateDeductionInfo Info(Loc);
4713 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4714 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004715
4716 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004717 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004718
4719 return Better1 ? PS1 : PS2;
4720}
4721
Richard Smith0e617ec2016-12-27 07:56:27 +00004722bool Sema::isMoreSpecializedThanPrimary(
4723 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4724 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4725 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4726 QualType PartialT = Spec->getInjectedSpecializationType();
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
Larisse Voufo39a1e502013-08-06 01:03:05 +00004736VarTemplatePartialSpecializationDecl *
4737Sema::getMoreSpecializedPartialSpecialization(
4738 VarTemplatePartialSpecializationDecl *PS1,
4739 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004740 // Pretend the variable template specializations are class template
4741 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004742 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004743 "the partial specializations being compared should specialize"
4744 " the same template.");
4745 TemplateName Name(PS1->getSpecializedTemplate());
4746 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4747 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004748 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004749 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004750 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004751
Richard Smith0e617ec2016-12-27 07:56:27 +00004752 TemplateDeductionInfo Info(Loc);
4753 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4754 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755
Douglas Gregorbe999392009-09-15 16:23:51 +00004756 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004757 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Richard Smith0da6dc42016-12-24 16:40:51 +00004759 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004760}
4761
Richard Smith0e617ec2016-12-27 07:56:27 +00004762bool Sema::isMoreSpecializedThanPrimary(
4763 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4764 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4765 // FIXME: Cache the injected template arguments rather than recomputing
4766 // them for each partial specialization.
4767 SmallVector<TemplateArgument, 8> PrimaryArgs;
4768 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4769 PrimaryArgs);
4770
4771 TemplateName CanonTemplate =
4772 Context.getCanonicalTemplateName(TemplateName(Primary));
4773 QualType PrimaryT = Context.getTemplateSpecializationType(
4774 CanonTemplate, PrimaryArgs);
4775 QualType PartialT = Context.getTemplateSpecializationType(
4776 CanonTemplate, Spec->getTemplateArgs().asArray());
4777 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4778 return false;
4779 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4780 Info.clearSFINAEDiagnostic();
4781 return false;
4782 }
4783 return true;
4784}
4785
Richard Smith26b86ea2016-12-31 21:41:23 +00004786bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4787 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4788 // C++1z [temp.arg.template]p4: (DR 150)
4789 // A template template-parameter P is at least as specialized as a
4790 // template template-argument A if, given the following rewrite to two
4791 // function templates...
4792
4793 // Rather than synthesize function templates, we merely perform the
4794 // equivalent partial ordering by performing deduction directly on
4795 // the template parameter lists of the template template parameters.
4796 //
4797 // Given an invented class template X with the template parameter list of
4798 // A (including default arguments):
4799 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4800 TemplateParameterList *A = AArg->getTemplateParameters();
4801
4802 // - Each function template has a single function parameter whose type is
4803 // a specialization of X with template arguments corresponding to the
4804 // template parameters from the respective function template
4805 SmallVector<TemplateArgument, 8> AArgs;
4806 Context.getInjectedTemplateArgs(A, AArgs);
4807
4808 // Check P's arguments against A's parameter list. This will fill in default
4809 // template arguments as needed. AArgs are already correct by construction.
4810 // We can't just use CheckTemplateIdType because that will expand alias
4811 // templates.
4812 SmallVector<TemplateArgument, 4> PArgs;
4813 {
4814 SFINAETrap Trap(*this);
4815
4816 Context.getInjectedTemplateArgs(P, PArgs);
4817 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4818 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4819 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4820 // expansions, to form an "as written" argument list.
4821 TemplateArgument Arg = PArgs[I];
4822 if (Arg.getKind() == TemplateArgument::Pack) {
4823 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4824 Arg = *Arg.pack_begin();
4825 }
4826 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4827 Arg, QualType(), P->getParam(I)->getLocation()));
4828 }
4829 PArgs.clear();
4830
4831 // C++1z [temp.arg.template]p3:
4832 // If the rewrite produces an invalid type, then P is not at least as
4833 // specialized as A.
4834 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4835 Trap.hasErrorOccurred())
4836 return false;
4837 }
4838
4839 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4840 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4841
Richard Smith26b86ea2016-12-31 21:41:23 +00004842 // ... the function template corresponding to P is at least as specialized
4843 // as the function template corresponding to A according to the partial
4844 // ordering rules for function templates.
4845 TemplateDeductionInfo Info(Loc, A->getDepth());
4846 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4847}
4848
Mike Stump11289f42009-09-09 15:08:12 +00004849static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004850MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004851 const TemplateArgument &TemplateArg,
4852 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004853 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004854 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004855
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004856/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004857/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004858static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004859MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004860 const Expr *E,
4861 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004862 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004863 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004864 // We can deduce from a pack expansion.
4865 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4866 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867
Richard Smith34349002012-07-09 03:07:20 +00004868 // Skip through any implicit casts we added while type-checking, and any
4869 // substitutions performed by template alias expansion.
4870 while (1) {
4871 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4872 E = ICE->getSubExpr();
4873 else if (const SubstNonTypeTemplateParmExpr *Subst =
4874 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4875 E = Subst->getReplacement();
4876 else
4877 break;
4878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
4880 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004881 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004882 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004883 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004884 return;
4885
Mike Stump11289f42009-09-09 15:08:12 +00004886 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004887 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4888 if (!NTTP)
4889 return;
4890
Douglas Gregor21610382009-10-29 00:04:11 +00004891 if (NTTP->getDepth() == Depth)
4892 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004893
4894 // In C++1z mode, additional arguments may be deduced from the type of a
4895 // non-type argument.
4896 if (Ctx.getLangOpts().CPlusPlus1z)
4897 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004898}
4899
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004900/// \brief Mark the template parameters that are used by the given
4901/// nested name specifier.
4902static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004903MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004904 NestedNameSpecifier *NNS,
4905 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004906 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004907 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004908 if (!NNS)
4909 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004911 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004912 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004914 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004915}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004917/// \brief Mark the template parameters that are used by the given
4918/// template name.
4919static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004920MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004921 TemplateName Name,
4922 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004923 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004924 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004925 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4926 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004927 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4928 if (TTP->getDepth() == Depth)
4929 Used[TTP->getIndex()] = true;
4930 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004931 return;
4932 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004934 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004936 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004937 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004938 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004939 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004940}
4941
4942/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004943/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004944static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004945MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004946 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004947 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004948 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004949 if (T.isNull())
4950 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004951
Douglas Gregor91772d12009-06-13 00:26:55 +00004952 // Non-dependent types have nothing deducible
4953 if (!T->isDependentType())
4954 return;
4955
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004956 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004957 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004958 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004960 cast<PointerType>(T)->getPointeeType(),
4961 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004962 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004963 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004964 break;
4965
4966 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004967 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004968 cast<BlockPointerType>(T)->getPointeeType(),
4969 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004970 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004971 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004972 break;
4973
4974 case Type::LValueReference:
4975 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004976 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004977 cast<ReferenceType>(T)->getPointeeType(),
4978 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004979 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004980 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004981 break;
4982
4983 case Type::MemberPointer: {
4984 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004985 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004986 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004987 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004988 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004989 break;
4990 }
4991
4992 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004993 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004994 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004995 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004996 // Fall through to check the element type
4997
4998 case Type::ConstantArray:
4999 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005000 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005001 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005002 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005003 break;
5004
5005 case Type::Vector:
5006 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005007 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005008 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005009 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005010 break;
5011
Douglas Gregor758a8692009-06-17 21:51:59 +00005012 case Type::DependentSizedExtVector: {
5013 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005014 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005015 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005016 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005017 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005018 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005019 break;
5020 }
5021
Douglas Gregor91772d12009-06-13 00:26:55 +00005022 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005023 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005024 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5025 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005026 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5027 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005028 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005029 break;
5030 }
5031
Douglas Gregor21610382009-10-29 00:04:11 +00005032 case Type::TemplateTypeParm: {
5033 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5034 if (TTP->getDepth() == Depth)
5035 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005036 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005037 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005038
Douglas Gregorfb322d82011-01-14 05:11:40 +00005039 case Type::SubstTemplateTypeParmPack: {
5040 const SubstTemplateTypeParmPackType *Subst
5041 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005042 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005043 QualType(Subst->getReplacedParameter(), 0),
5044 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005045 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005046 OnlyDeduced, Depth, Used);
5047 break;
5048 }
5049
John McCall2408e322010-04-27 00:57:59 +00005050 case Type::InjectedClassName:
5051 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5052 // fall through
5053
Douglas Gregor91772d12009-06-13 00:26:55 +00005054 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005055 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005056 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005057 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005058 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
Douglas Gregord0ad2942010-12-23 01:24:45 +00005060 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005061 // If the template argument list of P contains a pack expansion that is
5062 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005063 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005065 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005066 break;
5067
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005068 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005069 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005070 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005071 break;
5072 }
5073
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005074 case Type::Complex:
5075 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005076 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005077 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005078 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005079 break;
5080
Eli Friedman0dfb8892011-10-06 23:00:33 +00005081 case Type::Atomic:
5082 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005083 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005084 cast<AtomicType>(T)->getValueType(),
5085 OnlyDeduced, Depth, Used);
5086 break;
5087
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005088 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005089 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005090 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005091 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005092 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005093 break;
5094
John McCallc392f372010-06-11 00:33:02 +00005095 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005096 // C++14 [temp.deduct.type]p5:
5097 // The non-deduced contexts are:
5098 // -- The nested-name-specifier of a type that was specified using a
5099 // qualified-id
5100 //
5101 // C++14 [temp.deduct.type]p6:
5102 // When a type name is specified in a way that includes a non-deduced
5103 // context, all of the types that comprise that type name are also
5104 // non-deduced.
5105 if (OnlyDeduced)
5106 break;
5107
John McCallc392f372010-06-11 00:33:02 +00005108 const DependentTemplateSpecializationType *Spec
5109 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110
Richard Smith50d5b972015-12-30 20:56:05 +00005111 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5112 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005113
John McCallc392f372010-06-11 00:33:02 +00005114 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005115 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005116 Used);
5117 break;
5118 }
5119
John McCallbd8d9bd2010-03-01 23:49:17 +00005120 case Type::TypeOf:
5121 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005122 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005123 cast<TypeOfType>(T)->getUnderlyingType(),
5124 OnlyDeduced, Depth, Used);
5125 break;
5126
5127 case Type::TypeOfExpr:
5128 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005129 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005130 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5131 OnlyDeduced, Depth, Used);
5132 break;
5133
5134 case Type::Decltype:
5135 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005136 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005137 cast<DecltypeType>(T)->getUnderlyingExpr(),
5138 OnlyDeduced, Depth, Used);
5139 break;
5140
Alexis Hunte852b102011-05-24 22:41:36 +00005141 case Type::UnaryTransform:
5142 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005143 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005144 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005145 OnlyDeduced, Depth, Used);
5146 break;
5147
Douglas Gregord2fa7662010-12-20 02:24:11 +00005148 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005149 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005150 cast<PackExpansionType>(T)->getPattern(),
5151 OnlyDeduced, Depth, Used);
5152 break;
5153
Richard Smith30482bc2011-02-20 03:19:35 +00005154 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005155 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005156 cast<AutoType>(T)->getDeducedType(),
5157 OnlyDeduced, Depth, Used);
5158
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005159 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005160 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005161 case Type::VariableArray:
5162 case Type::FunctionNoProto:
5163 case Type::Record:
5164 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005165 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005166 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005167 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005168 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005169 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005170#define TYPE(Class, Base)
5171#define ABSTRACT_TYPE(Class, Base)
5172#define DEPENDENT_TYPE(Class, Base)
5173#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5174#include "clang/AST/TypeNodes.def"
5175 break;
5176 }
5177}
5178
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005179/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005180/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005181static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005182MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005183 const TemplateArgument &TemplateArg,
5184 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005185 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005186 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005187 switch (TemplateArg.getKind()) {
5188 case TemplateArgument::Null:
5189 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005190 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005191 break;
Mike Stump11289f42009-09-09 15:08:12 +00005192
Eli Friedmanb826a002012-09-26 02:36:12 +00005193 case TemplateArgument::NullPtr:
5194 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5195 Depth, Used);
5196 break;
5197
Douglas Gregor91772d12009-06-13 00:26:55 +00005198 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005199 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005200 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005201 break;
5202
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005203 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005204 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005205 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005206 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005207 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005208 break;
5209
5210 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005211 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005212 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005213 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214
Anders Carlssonbc343912009-06-15 17:04:53 +00005215 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005216 for (const auto &P : TemplateArg.pack_elements())
5217 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005218 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005219 }
5220}
5221
James Dennett41725122012-06-22 10:16:05 +00005222/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005223/// template argument list.
5224///
5225/// \param TemplateArgs the template argument list from which template
5226/// parameters will be deduced.
5227///
James Dennett41725122012-06-22 10:16:05 +00005228/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005229/// to indicate when the corresponding template parameter will be
5230/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005231void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005232Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005233 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005234 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005235 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005236 // If the template argument list of P contains a pack expansion that is not
5237 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005238 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005239 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005240 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005241 return;
5242
Douglas Gregor91772d12009-06-13 00:26:55 +00005243 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005244 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005245 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005246}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005247
5248/// \brief Marks all of the template parameters that will be deduced by a
5249/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005250void Sema::MarkDeducedTemplateParameters(
5251 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5252 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005254 = FunctionTemplate->getTemplateParameters();
5255 Deduced.clear();
5256 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005257
Douglas Gregorce23bae2009-09-18 23:21:38 +00005258 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5259 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005260 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005261 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005262}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005263
5264bool hasDeducibleTemplateParameters(Sema &S,
5265 FunctionTemplateDecl *FunctionTemplate,
5266 QualType T) {
5267 if (!T->isDependentType())
5268 return false;
5269
5270 TemplateParameterList *TemplateParams
5271 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005272 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005273 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005274 Deduced);
5275
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005276 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005277}